From f29a5d0b2dc94ed1a54c7bb27eea2360c5d49902 Mon Sep 17 00:00:00 2001 From: Fernando Panizza Date: Fri, 1 Sep 2023 10:12:36 -0300 Subject: [PATCH 1/2] remove apache Android from pom files. --- README.md | 1 - pom.xml | 1 - 2 files changed, 2 deletions(-) diff --git a/README.md b/README.md index 611e146a9..a6188c173 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,6 @@ These are the source of the GeneXus Standard Classes for Java, valid since GeneX |---|--- | common | Classes common to Android and Java | gxcryptocommon | Classes common to Android and Java related to Cryptography -| apacheandroid | Android apache class dependence. These were separated by size issues. They are candidates to disappear in the near future | gxmail | Classes related to mail handling | java | Java standard classes, output is gxclassr.jar | wrappercommon | Interfaces to encapsulate Java EE and Jakarta EE support, output is gxwrappercommon.jar diff --git a/pom.xml b/pom.xml index c3e25eff0..2a246328d 100644 --- a/pom.xml +++ b/pom.xml @@ -93,7 +93,6 @@ gxoffice gxsearch javapns - apacheandroid android gxgeospatial gxodata From 5ed3e540f456bb963132282fa0d9240905e5e0d1 Mon Sep 17 00:00:00 2001 From: Fernando Panizza Date: Fri, 1 Sep 2023 10:13:42 -0300 Subject: [PATCH 2/2] remove apache Android source code. --- apacheandroid/pom.xml | 19 - .../org/apache/commons/io/ByteOrderMark.java | 184 -- .../org/apache/commons/io/EndianUtils.java | 488 --- .../commons/io/FileExistsException.java | 60 - .../java/org/apache/commons/io/FileUtils.java | 2687 ----------------- .../org/apache/commons/io/FilenameUtils.java | 1401 --------- .../java/org/apache/commons/io/IOCase.java | 256 -- .../commons/io/IOExceptionWithCause.java | 68 - .../java/org/apache/commons/io/IOUtils.java | 2218 -------------- .../org/apache/commons/io/LineIterator.java | 180 -- .../apache/commons/io/TaggedIOException.java | 135 - .../io/filefilter/AbstractFileFilter.java | 64 - .../io/filefilter/DirectoryFileFilter.java | 73 - .../commons/io/filefilter/FileFileFilter.java | 62 - .../io/filefilter/FileFilterUtils.java | 358 --- .../commons/io/filefilter/IOFileFilter.java | 53 - .../commons/io/filefilter/NameFileFilter.java | 192 -- .../io/input/CharSequenceInputStream.java | 206 -- .../commons/io/input/CharSequenceReader.java | 163 - .../commons/io/input/ClosedInputStream.java | 49 - .../commons/io/input/NullInputStream.java | 338 --- .../apache/commons/io/input/NullReader.java | 321 -- .../commons/io/input/ReaderInputStream.java | 294 -- .../io/output/ByteArrayOutputStream.java | 359 --- .../commons/io/output/ClosedOutputStream.java | 51 - .../io/output/FileWriterWithEncoding.java | 331 -- .../commons/io/output/NullOutputStream.java | 67 - .../apache/commons/io/output/NullWriter.java | 141 - .../io/output/StringBuilderWriter.java | 160 - .../commons/io/output/WriterOutputStream.java | 306 -- 30 files changed, 11284 deletions(-) delete mode 100644 apacheandroid/pom.xml delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/ByteOrderMark.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/EndianUtils.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/FileExistsException.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/FileUtils.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/FilenameUtils.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/IOCase.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/IOExceptionWithCause.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/IOUtils.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/LineIterator.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/TaggedIOException.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/filefilter/AbstractFileFilter.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/filefilter/DirectoryFileFilter.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/filefilter/FileFileFilter.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/filefilter/FileFilterUtils.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/filefilter/IOFileFilter.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/filefilter/NameFileFilter.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/input/CharSequenceInputStream.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/input/CharSequenceReader.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/input/ClosedInputStream.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/input/NullInputStream.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/input/NullReader.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/input/ReaderInputStream.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/output/ByteArrayOutputStream.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/output/ClosedOutputStream.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/output/FileWriterWithEncoding.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/output/NullOutputStream.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/output/NullWriter.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/output/StringBuilderWriter.java delete mode 100644 apacheandroid/src/main/java/org/apache/commons/io/output/WriterOutputStream.java diff --git a/apacheandroid/pom.xml b/apacheandroid/pom.xml deleted file mode 100644 index bac4069d5..000000000 --- a/apacheandroid/pom.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - 4.0.0 - - - com.genexus - parent - ${revision}${changelist} - - - apacheandroid - Apache Android classes - - - apacheandroid - - diff --git a/apacheandroid/src/main/java/org/apache/commons/io/ByteOrderMark.java b/apacheandroid/src/main/java/org/apache/commons/io/ByteOrderMark.java deleted file mode 100644 index 6499aa279..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/ByteOrderMark.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io; - -import java.io.Serializable; - -/** - * Byte Order Mark (BOM) representation - see {@link org.apache.commons.io.input.BOMInputStream}. - * - * @see org.apache.commons.io.input.BOMInputStream - * @see Wikipedia: Byte Order Mark - * @see W3C: Autodetection of Character Encodings - * (Non-Normative) - * @version $Id: ByteOrderMark.java 1304166 2012-03-23 02:35:48Z ggregory $ - * @since 2.0 - */ -public class ByteOrderMark implements Serializable { - - private static final long serialVersionUID = 1L; - - /** UTF-8 BOM */ - public static final ByteOrderMark UTF_8 = new ByteOrderMark("UTF-8", 0xEF, 0xBB, 0xBF); - - /** UTF-16BE BOM (Big-Endian) */ - public static final ByteOrderMark UTF_16BE = new ByteOrderMark("UTF-16BE", 0xFE, 0xFF); - - /** UTF-16LE BOM (Little-Endian) */ - public static final ByteOrderMark UTF_16LE = new ByteOrderMark("UTF-16LE", 0xFF, 0xFE); - - /** - * UFT-32BE BOM (Big-Endian) - * @since 2.2 - */ - public static final ByteOrderMark UTF_32BE = new ByteOrderMark("UTF-32BE", 0x00, 0x00, 0xFE, 0xFF); - - /** - * UTF-32LE BOM (Big-Endian) - * @since 2.2 - */ - public static final ByteOrderMark UTF_32LE = new ByteOrderMark("UTF-32LE", 0xFE, 0xFF, 0x00, 0x00); - - private final String charsetName; - private final int[] bytes; - - /** - * Construct a new BOM. - * - * @param charsetName The name of the charset the BOM represents - * @param bytes The BOM's bytes - * @throws IllegalArgumentException if the charsetName is null or - * zero length - * @throws IllegalArgumentException if the bytes are null or zero - * length - */ - public ByteOrderMark(String charsetName, int... bytes) { - if (charsetName == null || charsetName.length() == 0) { - throw new IllegalArgumentException("No charsetName specified"); - } - if (bytes == null || bytes.length == 0) { - throw new IllegalArgumentException("No bytes specified"); - } - this.charsetName = charsetName; - this.bytes = new int[bytes.length]; - System.arraycopy(bytes, 0, this.bytes, 0, bytes.length); - } - - /** - * Return the name of the {@link java.nio.charset.Charset} the BOM represents. - * - * @return the character set name - */ - public String getCharsetName() { - return charsetName; - } - - /** - * Return the length of the BOM's bytes. - * - * @return the length of the BOM's bytes - */ - public int length() { - return bytes.length; - } - - /** - * The byte at the specified position. - * - * @param pos The position - * @return The specified byte - */ - public int get(int pos) { - return bytes[pos]; - } - - /** - * Return a copy of the BOM's bytes. - * - * @return a copy of the BOM's bytes - */ - public byte[] getBytes() { - byte[] copy = new byte[bytes.length]; - for (int i = 0; i < bytes.length; i++) { - copy[i] = (byte)bytes[i]; - } - return copy; - } - - /** - * Indicates if this BOM's bytes equals another. - * - * @param obj The object to compare to - * @return true if the bom's bytes are equal, otherwise - * false - */ - @Override - public boolean equals(Object obj) { - if (!(obj instanceof ByteOrderMark)) { - return false; - } - ByteOrderMark bom = (ByteOrderMark)obj; - if (bytes.length != bom.length()) { - return false; - } - for (int i = 0; i < bytes.length; i++) { - if (bytes[i] != bom.get(i)) { - return false; - } - } - return true; - } - - /** - * Return the hashcode for this BOM. - * - * @return the hashcode for this BOM. - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - int hashCode = getClass().hashCode(); - for (int b : bytes) { - hashCode += b; - } - return hashCode; - } - - /** - * Provide a String representation of the BOM. - * - * @return the length of the BOM's bytes - */ - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append(getClass().getSimpleName()); - builder.append('['); - builder.append(charsetName); - builder.append(": "); - for (int i = 0; i < bytes.length; i++) { - if (i > 0) { - builder.append(","); - } - builder.append("0x"); - builder.append(Integer.toHexString(0xFF & bytes[i]).toUpperCase()); - } - builder.append(']'); - return builder.toString(); - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/EndianUtils.java b/apacheandroid/src/main/java/org/apache/commons/io/EndianUtils.java deleted file mode 100644 index a03d77c22..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/EndianUtils.java +++ /dev/null @@ -1,488 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io; - -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * Utility code for dealing with different endian systems. - *

- * Different computer architectures adopt different conventions for - * byte ordering. In so-called "Little Endian" architectures (eg Intel), - * the low-order byte is stored in memory at the lowest address, and - * subsequent bytes at higher addresses. For "Big Endian" architectures - * (eg Motorola), the situation is reversed. - * This class helps you solve this incompatability. - *

- * Origin of code: Excalibur - * - * @version $Id: EndianUtils.java 1302056 2012-03-18 03:03:38Z ggregory $ - * @see org.apache.commons.io.input.SwappedDataInputStream - */ -public class EndianUtils { - - /** - * Instances should NOT be constructed in standard programming. - */ - public EndianUtils() { - super(); - } - - // ========================================== Swapping routines - - /** - * Converts a "short" value between endian systems. - * @param value value to convert - * @return the converted value - */ - public static short swapShort(short value) { - return (short) ( ( ( ( value >> 0 ) & 0xff ) << 8 ) + - ( ( ( value >> 8 ) & 0xff ) << 0 ) ); - } - - /** - * Converts a "int" value between endian systems. - * @param value value to convert - * @return the converted value - */ - public static int swapInteger(int value) { - return - ( ( ( value >> 0 ) & 0xff ) << 24 ) + - ( ( ( value >> 8 ) & 0xff ) << 16 ) + - ( ( ( value >> 16 ) & 0xff ) << 8 ) + - ( ( ( value >> 24 ) & 0xff ) << 0 ); - } - - /** - * Converts a "long" value between endian systems. - * @param value value to convert - * @return the converted value - */ - public static long swapLong(long value) { - return - ( ( ( value >> 0 ) & 0xff ) << 56 ) + - ( ( ( value >> 8 ) & 0xff ) << 48 ) + - ( ( ( value >> 16 ) & 0xff ) << 40 ) + - ( ( ( value >> 24 ) & 0xff ) << 32 ) + - ( ( ( value >> 32 ) & 0xff ) << 24 ) + - ( ( ( value >> 40 ) & 0xff ) << 16 ) + - ( ( ( value >> 48 ) & 0xff ) << 8 ) + - ( ( ( value >> 56 ) & 0xff ) << 0 ); - } - - /** - * Converts a "float" value between endian systems. - * @param value value to convert - * @return the converted value - */ - public static float swapFloat(float value) { - return Float.intBitsToFloat( swapInteger( Float.floatToIntBits( value ) ) ); - } - - /** - * Converts a "double" value between endian systems. - * @param value value to convert - * @return the converted value - */ - public static double swapDouble(double value) { - return Double.longBitsToDouble( swapLong( Double.doubleToLongBits( value ) ) ); - } - - // ========================================== Swapping read/write routines - - /** - * Writes a "short" value to a byte array at a given offset. The value is - * converted to the opposed endian system while writing. - * @param data target byte array - * @param offset starting offset in the byte array - * @param value value to write - */ - public static void writeSwappedShort(byte[] data, int offset, short value) { - data[ offset + 0 ] = (byte)( ( value >> 0 ) & 0xff ); - data[ offset + 1 ] = (byte)( ( value >> 8 ) & 0xff ); - } - - /** - * Reads a "short" value from a byte array at a given offset. The value is - * converted to the opposed endian system while reading. - * @param data source byte array - * @param offset starting offset in the byte array - * @return the value read - */ - public static short readSwappedShort(byte[] data, int offset) { - return (short)( ( ( data[ offset + 0 ] & 0xff ) << 0 ) + - ( ( data[ offset + 1 ] & 0xff ) << 8 ) ); - } - - /** - * Reads an unsigned short (16-bit) value from a byte array at a given - * offset. The value is converted to the opposed endian system while - * reading. - * @param data source byte array - * @param offset starting offset in the byte array - * @return the value read - */ - public static int readSwappedUnsignedShort(byte[] data, int offset) { - return ( ( ( data[ offset + 0 ] & 0xff ) << 0 ) + - ( ( data[ offset + 1 ] & 0xff ) << 8 ) ); - } - - /** - * Writes a "int" value to a byte array at a given offset. The value is - * converted to the opposed endian system while writing. - * @param data target byte array - * @param offset starting offset in the byte array - * @param value value to write - */ - public static void writeSwappedInteger(byte[] data, int offset, int value) { - data[ offset + 0 ] = (byte)( ( value >> 0 ) & 0xff ); - data[ offset + 1 ] = (byte)( ( value >> 8 ) & 0xff ); - data[ offset + 2 ] = (byte)( ( value >> 16 ) & 0xff ); - data[ offset + 3 ] = (byte)( ( value >> 24 ) & 0xff ); - } - - /** - * Reads a "int" value from a byte array at a given offset. The value is - * converted to the opposed endian system while reading. - * @param data source byte array - * @param offset starting offset in the byte array - * @return the value read - */ - public static int readSwappedInteger(byte[] data, int offset) { - return ( ( ( data[ offset + 0 ] & 0xff ) << 0 ) + - ( ( data[ offset + 1 ] & 0xff ) << 8 ) + - ( ( data[ offset + 2 ] & 0xff ) << 16 ) + - ( ( data[ offset + 3 ] & 0xff ) << 24 ) ); - } - - /** - * Reads an unsigned integer (32-bit) value from a byte array at a given - * offset. The value is converted to the opposed endian system while - * reading. - * @param data source byte array - * @param offset starting offset in the byte array - * @return the value read - */ - public static long readSwappedUnsignedInteger(byte[] data, int offset) { - long low = ( ( ( data[ offset + 0 ] & 0xff ) << 0 ) + - ( ( data[ offset + 1 ] & 0xff ) << 8 ) + - ( ( data[ offset + 2 ] & 0xff ) << 16 ) ); - - long high = data[ offset + 3 ] & 0xff; - - return (high << 24) + (0xffffffffL & low); - } - - /** - * Writes a "long" value to a byte array at a given offset. The value is - * converted to the opposed endian system while writing. - * @param data target byte array - * @param offset starting offset in the byte array - * @param value value to write - */ - public static void writeSwappedLong(byte[] data, int offset, long value) { - data[ offset + 0 ] = (byte)( ( value >> 0 ) & 0xff ); - data[ offset + 1 ] = (byte)( ( value >> 8 ) & 0xff ); - data[ offset + 2 ] = (byte)( ( value >> 16 ) & 0xff ); - data[ offset + 3 ] = (byte)( ( value >> 24 ) & 0xff ); - data[ offset + 4 ] = (byte)( ( value >> 32 ) & 0xff ); - data[ offset + 5 ] = (byte)( ( value >> 40 ) & 0xff ); - data[ offset + 6 ] = (byte)( ( value >> 48 ) & 0xff ); - data[ offset + 7 ] = (byte)( ( value >> 56 ) & 0xff ); - } - - /** - * Reads a "long" value from a byte array at a given offset. The value is - * converted to the opposed endian system while reading. - * @param data source byte array - * @param offset starting offset in the byte array - * @return the value read - */ - public static long readSwappedLong(byte[] data, int offset) { - long low = - ( ( data[ offset + 0 ] & 0xff ) << 0 ) + - ( ( data[ offset + 1 ] & 0xff ) << 8 ) + - ( ( data[ offset + 2 ] & 0xff ) << 16 ) + - ( ( data[ offset + 3 ] & 0xff ) << 24 ); - long high = - ( ( data[ offset + 4 ] & 0xff ) << 0 ) + - ( ( data[ offset + 5 ] & 0xff ) << 8 ) + - ( ( data[ offset + 6 ] & 0xff ) << 16 ) + - ( ( data[ offset + 7 ] & 0xff ) << 24 ); - return (high << 32) + (0xffffffffL & low); - } - - /** - * Writes a "float" value to a byte array at a given offset. The value is - * converted to the opposed endian system while writing. - * @param data target byte array - * @param offset starting offset in the byte array - * @param value value to write - */ - public static void writeSwappedFloat(byte[] data, int offset, float value) { - writeSwappedInteger( data, offset, Float.floatToIntBits( value ) ); - } - - /** - * Reads a "float" value from a byte array at a given offset. The value is - * converted to the opposed endian system while reading. - * @param data source byte array - * @param offset starting offset in the byte array - * @return the value read - */ - public static float readSwappedFloat(byte[] data, int offset) { - return Float.intBitsToFloat( readSwappedInteger( data, offset ) ); - } - - /** - * Writes a "double" value to a byte array at a given offset. The value is - * converted to the opposed endian system while writing. - * @param data target byte array - * @param offset starting offset in the byte array - * @param value value to write - */ - public static void writeSwappedDouble(byte[] data, int offset, double value) { - writeSwappedLong( data, offset, Double.doubleToLongBits( value ) ); - } - - /** - * Reads a "double" value from a byte array at a given offset. The value is - * converted to the opposed endian system while reading. - * @param data source byte array - * @param offset starting offset in the byte array - * @return the value read - */ - public static double readSwappedDouble(byte[] data, int offset) { - return Double.longBitsToDouble( readSwappedLong( data, offset ) ); - } - - /** - * Writes a "short" value to an OutputStream. The value is - * converted to the opposed endian system while writing. - * @param output target OutputStream - * @param value value to write - * @throws IOException in case of an I/O problem - */ - public static void writeSwappedShort(OutputStream output, short value) - throws IOException - { - output.write( (byte)( ( value >> 0 ) & 0xff ) ); - output.write( (byte)( ( value >> 8 ) & 0xff ) ); - } - - /** - * Reads a "short" value from an InputStream. The value is - * converted to the opposed endian system while reading. - * @param input source InputStream - * @return the value just read - * @throws IOException in case of an I/O problem - */ - public static short readSwappedShort(InputStream input) - throws IOException - { - return (short)( ( ( read( input ) & 0xff ) << 0 ) + - ( ( read( input ) & 0xff ) << 8 ) ); - } - - /** - * Reads a unsigned short (16-bit) from an InputStream. The value is - * converted to the opposed endian system while reading. - * @param input source InputStream - * @return the value just read - * @throws IOException in case of an I/O problem - */ - public static int readSwappedUnsignedShort(InputStream input) - throws IOException - { - int value1 = read( input ); - int value2 = read( input ); - - return ( ( ( value1 & 0xff ) << 0 ) + - ( ( value2 & 0xff ) << 8 ) ); - } - - /** - * Writes a "int" value to an OutputStream. The value is - * converted to the opposed endian system while writing. - * @param output target OutputStream - * @param value value to write - * @throws IOException in case of an I/O problem - */ - public static void writeSwappedInteger(OutputStream output, int value) - throws IOException - { - output.write( (byte)( ( value >> 0 ) & 0xff ) ); - output.write( (byte)( ( value >> 8 ) & 0xff ) ); - output.write( (byte)( ( value >> 16 ) & 0xff ) ); - output.write( (byte)( ( value >> 24 ) & 0xff ) ); - } - - /** - * Reads a "int" value from an InputStream. The value is - * converted to the opposed endian system while reading. - * @param input source InputStream - * @return the value just read - * @throws IOException in case of an I/O problem - */ - public static int readSwappedInteger(InputStream input) - throws IOException - { - int value1 = read( input ); - int value2 = read( input ); - int value3 = read( input ); - int value4 = read( input ); - - return ( ( value1 & 0xff ) << 0 ) + - ( ( value2 & 0xff ) << 8 ) + - ( ( value3 & 0xff ) << 16 ) + - ( ( value4 & 0xff ) << 24 ); - } - - /** - * Reads a unsigned integer (32-bit) from an InputStream. The value is - * converted to the opposed endian system while reading. - * @param input source InputStream - * @return the value just read - * @throws IOException in case of an I/O problem - */ - public static long readSwappedUnsignedInteger(InputStream input) - throws IOException - { - int value1 = read( input ); - int value2 = read( input ); - int value3 = read( input ); - int value4 = read( input ); - - long low = ( ( ( value1 & 0xff ) << 0 ) + - ( ( value2 & 0xff ) << 8 ) + - ( ( value3 & 0xff ) << 16 ) ); - - long high = value4 & 0xff; - - return (high << 24) + (0xffffffffL & low); - } - - /** - * Writes a "long" value to an OutputStream. The value is - * converted to the opposed endian system while writing. - * @param output target OutputStream - * @param value value to write - * @throws IOException in case of an I/O problem - */ - public static void writeSwappedLong(OutputStream output, long value) - throws IOException - { - output.write( (byte)( ( value >> 0 ) & 0xff ) ); - output.write( (byte)( ( value >> 8 ) & 0xff ) ); - output.write( (byte)( ( value >> 16 ) & 0xff ) ); - output.write( (byte)( ( value >> 24 ) & 0xff ) ); - output.write( (byte)( ( value >> 32 ) & 0xff ) ); - output.write( (byte)( ( value >> 40 ) & 0xff ) ); - output.write( (byte)( ( value >> 48 ) & 0xff ) ); - output.write( (byte)( ( value >> 56 ) & 0xff ) ); - } - - /** - * Reads a "long" value from an InputStream. The value is - * converted to the opposed endian system while reading. - * @param input source InputStream - * @return the value just read - * @throws IOException in case of an I/O problem - */ - public static long readSwappedLong(InputStream input) - throws IOException - { - byte[] bytes = new byte[8]; - for ( int i=0; i<8; i++ ) { - bytes[i] = (byte) read( input ); - } - return readSwappedLong( bytes, 0 ); - } - - /** - * Writes a "float" value to an OutputStream. The value is - * converted to the opposed endian system while writing. - * @param output target OutputStream - * @param value value to write - * @throws IOException in case of an I/O problem - */ - public static void writeSwappedFloat(OutputStream output, float value) - throws IOException - { - writeSwappedInteger( output, Float.floatToIntBits( value ) ); - } - - /** - * Reads a "float" value from an InputStream. The value is - * converted to the opposed endian system while reading. - * @param input source InputStream - * @return the value just read - * @throws IOException in case of an I/O problem - */ - public static float readSwappedFloat(InputStream input) - throws IOException - { - return Float.intBitsToFloat( readSwappedInteger( input ) ); - } - - /** - * Writes a "double" value to an OutputStream. The value is - * converted to the opposed endian system while writing. - * @param output target OutputStream - * @param value value to write - * @throws IOException in case of an I/O problem - */ - public static void writeSwappedDouble(OutputStream output, double value) - throws IOException - { - writeSwappedLong( output, Double.doubleToLongBits( value ) ); - } - - /** - * Reads a "double" value from an InputStream. The value is - * converted to the opposed endian system while reading. - * @param input source InputStream - * @return the value just read - * @throws IOException in case of an I/O problem - */ - public static double readSwappedDouble(InputStream input) - throws IOException - { - return Double.longBitsToDouble( readSwappedLong( input ) ); - } - - /** - * Reads the next byte from the input stream. - * @param input the stream - * @return the byte - * @throws IOException if the end of file is reached - */ - private static int read(InputStream input) - throws IOException - { - int value = input.read(); - - if( -1 == value ) { - throw new EOFException( "Unexpected EOF reached" ); - } - - return value; - } -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/FileExistsException.java b/apacheandroid/src/main/java/org/apache/commons/io/FileExistsException.java deleted file mode 100644 index 0cf746689..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/FileExistsException.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io; - -import java.io.File; -import java.io.IOException; - -/** - * Indicates that a file already exists. - * - * @version $Id: FileExistsException.java 1304052 2012-03-22 20:55:29Z ggregory $ - * @since 2.0 - */ -public class FileExistsException extends IOException { - - /** - * Defines the serial version UID. - */ - private static final long serialVersionUID = 1L; - - /** - * Default Constructor. - */ - public FileExistsException() { - super(); - } - - /** - * Construct an instance with the specified message. - * - * @param message The error message - */ - public FileExistsException(String message) { - super(message); - } - - /** - * Construct an instance with the specified file. - * - * @param file The file that exists - */ - public FileExistsException(File file) { - super("File " + file + " exists"); - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/FileUtils.java b/apacheandroid/src/main/java/org/apache/commons/io/FileUtils.java deleted file mode 100644 index 52b8d4499..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/FileUtils.java +++ /dev/null @@ -1,2687 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io; - -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.Reader; -import java.math.BigInteger; -import java.net.URL; -import java.net.URLConnection; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.zip.CRC32; -import java.util.zip.CheckedInputStream; -import java.util.zip.Checksum; - -import org.apache.commons.io.filefilter.IOFileFilter; -import org.apache.commons.io.output.NullOutputStream; - -/** - * General file manipulation utilities. - *

- * Facilities are provided in the following areas: - *

- *

- * Origin of code: Excalibur, Alexandria, Commons-Utils - * - * @version $Id: FileUtils.java 1304052 2012-03-22 20:55:29Z ggregory $ - */ -public class FileUtils { - - /** - * Instances should NOT be constructed in standard programming. - */ - public FileUtils() { - super(); - } - - /** - * The number of bytes in a kilobyte. - */ - public static final long ONE_KB = 1024; - - /** - * The number of bytes in a megabyte. - */ - public static final long ONE_MB = ONE_KB * ONE_KB; - - /** - * The file copy buffer size (30 MB) - */ - private static final long FILE_COPY_BUFFER_SIZE = ONE_MB * 30; - - /** - * The number of bytes in a gigabyte. - */ - public static final long ONE_GB = ONE_KB * ONE_MB; - - /** - * The number of bytes in a terabyte. - */ - public static final long ONE_TB = ONE_KB * ONE_GB; - - /** - * The number of bytes in a petabyte. - */ - public static final long ONE_PB = ONE_KB * ONE_TB; - - /** - * The number of bytes in an exabyte. - */ - public static final long ONE_EB = ONE_KB * ONE_PB; - - /** - * The number of bytes in a zettabyte. - */ - public static final BigInteger ONE_ZB = BigInteger.valueOf(ONE_KB).multiply(BigInteger.valueOf(ONE_EB)); - - /** - * The number of bytes in a yottabyte. - */ - public static final BigInteger ONE_YB = ONE_ZB.multiply(BigInteger.valueOf(ONE_EB)); - - /** - * An empty array of type File. - */ - public static final File[] EMPTY_FILE_ARRAY = new File[0]; - - /** - * The UTF-8 character set, used to decode octets in URLs. - */ - private static final Charset UTF8 = Charset.forName("UTF-8"); - - //----------------------------------------------------------------------- - /** - * Construct a file from the set of name elements. - * - * @param directory the parent directory - * @param names the name elements - * @return the file - * @since 2.1 - */ - public static File getFile(File directory, String... names) { - if (directory == null) { - throw new NullPointerException("directorydirectory must not be null"); - } - if (names == null) { - throw new NullPointerException("names must not be null"); - } - File file = directory; - for (String name : names) { - file = new File(file, name); - } - return file; - } - - /** - * Construct a file from the set of name elements. - * - * @param names the name elements - * @return the file - * @since 2.1 - */ - public static File getFile(String... names) { - if (names == null) { - throw new NullPointerException("names must not be null"); - } - File file = null; - for (String name : names) { - if (file == null) { - file = new File(name); - } else { - file = new File(file, name); - } - } - return file; - } - - /** - * Returns the path to the system temporary directory. - * - * @return the path to the system temporary directory. - * - * @since 2.0 - */ - public static String getTempDirectoryPath() { - return System.getProperty("java.io.tmpdir"); - } - - /** - * Returns a {@link File} representing the system temporary directory. - * - * @return the system temporary directory. - * - * @since 2.0 - */ - public static File getTempDirectory() { - return new File(getTempDirectoryPath()); - } - - /** - * Returns the path to the user's home directory. - * - * @return the path to the user's home directory. - * - * @since 2.0 - */ - public static String getUserDirectoryPath() { - return System.getProperty("user.home"); - } - - /** - * Returns a {@link File} representing the user's home directory. - * - * @return the user's home directory. - * - * @since 2.0 - */ - public static File getUserDirectory() { - return new File(getUserDirectoryPath()); - } - - //----------------------------------------------------------------------- - /** - * Opens a {@link FileInputStream} for the specified file, providing better - * error messages than simply calling new FileInputStream(file). - *

- * At the end of the method either the stream will be successfully opened, - * or an exception will have been thrown. - *

- * An exception is thrown if the file does not exist. - * An exception is thrown if the file object exists but is a directory. - * An exception is thrown if the file exists but cannot be read. - * - * @param file the file to open for input, must not be null - * @return a new {@link FileInputStream} for the specified file - * @throws FileNotFoundException if the file does not exist - * @throws IOException if the file object is a directory - * @throws IOException if the file cannot be read - * @since 1.3 - */ - public static FileInputStream openInputStream(File file) throws IOException { - if (file.exists()) { - if (file.isDirectory()) { - throw new IOException("File '" + file + "' exists but is a directory"); - } - if (file.canRead() == false) { - throw new IOException("File '" + file + "' cannot be read"); - } - } else { - throw new FileNotFoundException("File '" + file + "' does not exist"); - } - return new FileInputStream(file); - } - - //----------------------------------------------------------------------- - /** - * Opens a {@link FileOutputStream} for the specified file, checking and - * creating the parent directory if it does not exist. - *

- * At the end of the method either the stream will be successfully opened, - * or an exception will have been thrown. - *

- * The parent directory will be created if it does not exist. - * The file will be created if it does not exist. - * An exception is thrown if the file object exists but is a directory. - * An exception is thrown if the file exists but cannot be written to. - * An exception is thrown if the parent directory cannot be created. - * - * @param file the file to open for output, must not be null - * @return a new {@link FileOutputStream} for the specified file - * @throws IOException if the file object is a directory - * @throws IOException if the file cannot be written to - * @throws IOException if a parent directory needs creating but that fails - * @since 1.3 - */ - public static FileOutputStream openOutputStream(File file) throws IOException { - return openOutputStream(file, false); - } - - /** - * Opens a {@link FileOutputStream} for the specified file, checking and - * creating the parent directory if it does not exist. - *

- * At the end of the method either the stream will be successfully opened, - * or an exception will have been thrown. - *

- * The parent directory will be created if it does not exist. - * The file will be created if it does not exist. - * An exception is thrown if the file object exists but is a directory. - * An exception is thrown if the file exists but cannot be written to. - * An exception is thrown if the parent directory cannot be created. - * - * @param file the file to open for output, must not be null - * @param append if true, then bytes will be added to the - * end of the file rather than overwriting - * @return a new {@link FileOutputStream} for the specified file - * @throws IOException if the file object is a directory - * @throws IOException if the file cannot be written to - * @throws IOException if a parent directory needs creating but that fails - * @since 2.1 - */ - public static FileOutputStream openOutputStream(File file, boolean append) throws IOException { - if (file.exists()) { - if (file.isDirectory()) { - throw new IOException("File '" + file + "' exists but is a directory"); - } - if (file.canWrite() == false) { - throw new IOException("File '" + file + "' cannot be written to"); - } - } else { - File parent = file.getParentFile(); - if (parent != null) { - if (!parent.mkdirs() && !parent.isDirectory()) { - throw new IOException("Directory '" + parent + "' could not be created"); - } - } - } - return new FileOutputStream(file, append); - } - - //----------------------------------------------------------------------- - /** - * Returns a human-readable version of the file size, where the input - * represents a specific number of bytes. - * - * If the size is over 1GB, the size is returned as the number of whole GB, - * i.e. the size is rounded down to the nearest GB boundary. - * - * Similarly for the 1MB and 1KB boundaries. - * - * @param size the number of bytes - * @return a human-readable display value (includes units - GB, MB, KB or bytes) - */ - // See https://issues.apache.org/jira/browse/IO-226 - should the rounding be changed? - public static String byteCountToDisplaySize(long size) { - String displaySize; - - if (size / ONE_EB > 0) { - displaySize = String.valueOf(size / ONE_EB) + " EB"; - } else if (size / ONE_PB > 0) { - displaySize = String.valueOf(size / ONE_PB) + " PB"; - } else if (size / ONE_TB > 0) { - displaySize = String.valueOf(size / ONE_TB) + " TB"; - } else if (size / ONE_GB > 0) { - displaySize = String.valueOf(size / ONE_GB) + " GB"; - } else if (size / ONE_MB > 0) { - displaySize = String.valueOf(size / ONE_MB) + " MB"; - } else if (size / ONE_KB > 0) { - displaySize = String.valueOf(size / ONE_KB) + " KB"; - } else { - displaySize = String.valueOf(size) + " bytes"; - } - return displaySize; - } - - //----------------------------------------------------------------------- - /** - * Implements the same behaviour as the "touch" utility on Unix. It creates - * a new file with size 0 or, if the file exists already, it is opened and - * closed without modifying it, but updating the file date and time. - *

- * NOTE: As from v1.3, this method throws an IOException if the last - * modified date of the file cannot be set. Also, as from v1.3 this method - * creates parent directories if they do not exist. - * - * @param file the File to touch - * @throws IOException If an I/O problem occurs - */ - public static void touch(File file) throws IOException { - if (!file.exists()) { - OutputStream out = openOutputStream(file); - IOUtils.closeQuietly(out); - } - boolean success = file.setLastModified(System.currentTimeMillis()); - if (!success) { - throw new IOException("Unable to set the last modification time for " + file); - } - } - - //----------------------------------------------------------------------- - /** - * Converts a Collection containing java.io.File instanced into array - * representation. This is to account for the difference between - * File.listFiles() and FileUtils.listFiles(). - * - * @param files a Collection containing java.io.File instances - * @return an array of java.io.File - */ - public static File[] convertFileCollectionToFileArray(Collection files) { - return files.toArray(new File[files.size()]); - } - - //----------------------------------------------------------------------- - /** - * Finds files within a given directory (and optionally its - * subdirectories). All files found are filtered by an IOFileFilter. - * - * @param files the collection of files found. - * @param directory the directory to search in. - * @param filter the filter to apply to files and directories. - * @param includeSubDirectories indicates if will include the subdirectories themselves - */ - private static void innerListFiles(Collection files, File directory, - IOFileFilter filter, boolean includeSubDirectories) { - File[] found = directory.listFiles((FileFilter) filter); - - if (found != null) { - for (File file : found) { - if (file.isDirectory()) { - if (includeSubDirectories) { - files.add(file); - } - innerListFiles(files, file, filter, includeSubDirectories); - } else { - files.add(file); - } - } - } - } - - /** - * Finds files within a given directory (and optionally its - * subdirectories). All files found are filtered by an IOFileFilter. - *

- * If your search should recurse into subdirectories you can pass in - * an IOFileFilter for directories. You don't need to bind a - * DirectoryFileFilter (via logical AND) to this filter. This method does - * that for you. - *

- * An example: If you want to search through all directories called - * "temp" you pass in FileFilterUtils.NameFileFilter("temp") - *

- * Another common usage of this method is find files in a directory - * tree but ignoring the directories generated CVS. You can simply pass - * in FileFilterUtils.makeCVSAware(null). - * - * @param directory the directory to search in - * @param fileFilter filter to apply when finding files. - * @param dirFilter optional filter to apply when finding subdirectories. - * If this parameter is null, subdirectories will not be included in the - * search. Use TrueFileFilter.INSTANCE to match all directories. - * @return an collection of java.io.File with the matching files - * @see org.apache.commons.io.filefilter.FileFilterUtils - * @see org.apache.commons.io.filefilter.NameFileFilter - */ - /* - public static Collection listFiles( - File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) { - validateListFilesParameters(directory, fileFilter); - - IOFileFilter effFileFilter = setUpEffectiveFileFilter(fileFilter); - IOFileFilter effDirFilter = setUpEffectiveDirFilter(dirFilter); - - //Find files - Collection files = new java.util.LinkedList(); - innerListFiles(files, directory, - FileFilterUtils.or(effFileFilter, effDirFilter), false); - return files; - } -*/ - /** - * Validates the given arguments. - *

- * - * @param directory The File to test - * @param fileFilter The IOFileFilter to test - */ - private static void validateListFilesParameters(File directory, IOFileFilter fileFilter) { - if (!directory.isDirectory()) { - throw new IllegalArgumentException("Parameter 'directory' is not a directory"); - } - if (fileFilter == null) { - throw new NullPointerException("Parameter 'fileFilter' is null"); - } - } - - /** - * Returns a filter that accepts files in addition to the {@link File} objects accepted by the given filter. - * - * @param fileFilter a base filter to add to - * @return a filter that accepts files - */ - /* - private static IOFileFilter setUpEffectiveFileFilter(IOFileFilter fileFilter) { - return FileFilterUtils.and(fileFilter, FileFilterUtils.notFileFilter(DirectoryFileFilter.INSTANCE)); - } -*/ - /** - * Returns a filter that accepts directories in addition to the {@link File} objects accepted by the given filter. - * - * @param dirFilter a base filter to add to - * @return a filter that accepts directories - */ - /* - private static IOFileFilter setUpEffectiveDirFilter(IOFileFilter dirFilter) { - return dirFilter == null ? FalseFileFilter.INSTANCE : FileFilterUtils.and(dirFilter, - DirectoryFileFilter.INSTANCE); - } -*/ - /** - * Finds files within a given directory (and optionally its - * subdirectories). All files found are filtered by an IOFileFilter. - *

- * The resulting collection includes the subdirectories themselves. - *

- * @see org.apache.commons.io.FileUtils#listFiles - * - * @param directory the directory to search in - * @param fileFilter filter to apply when finding files. - * @param dirFilter optional filter to apply when finding subdirectories. - * If this parameter is null, subdirectories will not be included in the - * search. Use TrueFileFilter.INSTANCE to match all directories. - * @return an collection of java.io.File with the matching files - * @see org.apache.commons.io.filefilter.FileFilterUtils - * @see org.apache.commons.io.filefilter.NameFileFilter - * @since 2.2 - */ - /* - public static Collection listFilesAndDirs( - File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) { - validateListFilesParameters(directory, fileFilter); - - IOFileFilter effFileFilter = setUpEffectiveFileFilter(fileFilter); - IOFileFilter effDirFilter = setUpEffectiveDirFilter(dirFilter); - - //Find files - Collection files = new java.util.LinkedList(); - if (directory.isDirectory()) { - files.add(directory); - } - innerListFiles(files, directory, - FileFilterUtils.or(effFileFilter, effDirFilter), true); - return files; - } -*/ - /** - * Allows iteration over the files in given directory (and optionally - * its subdirectories). - *

- * All files found are filtered by an IOFileFilter. This method is - * based on {@link #listFiles(File, IOFileFilter, IOFileFilter)}, - * which supports Iterable ('foreach' loop). - *

- * @param directory the directory to search in - * @param fileFilter filter to apply when finding files. - * @param dirFilter optional filter to apply when finding subdirectories. - * If this parameter is null, subdirectories will not be included in the - * search. Use TrueFileFilter.INSTANCE to match all directories. - * @return an iterator of java.io.File for the matching files - * @see org.apache.commons.io.filefilter.FileFilterUtils - * @see org.apache.commons.io.filefilter.NameFileFilter - * @since 1.2 - */ - /* - public static Iterator iterateFiles( - File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) { - return listFiles(directory, fileFilter, dirFilter).iterator(); - } -*/ - /** - * Allows iteration over the files in given directory (and optionally - * its subdirectories). - *

- * All files found are filtered by an IOFileFilter. This method is - * based on {@link #listFilesAndDirs(File, IOFileFilter, IOFileFilter)}, - * which supports Iterable ('foreach' loop). - *

- * The resulting iterator includes the subdirectories themselves. - * - * @param directory the directory to search in - * @param fileFilter filter to apply when finding files. - * @param dirFilter optional filter to apply when finding subdirectories. - * If this parameter is null, subdirectories will not be included in the - * search. Use TrueFileFilter.INSTANCE to match all directories. - * @return an iterator of java.io.File for the matching files - * @see org.apache.commons.io.filefilter.FileFilterUtils - * @see org.apache.commons.io.filefilter.NameFileFilter - * @since 2.2 - */ - /* - public static Iterator iterateFilesAndDirs(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) { - return listFilesAndDirs(directory, fileFilter, dirFilter).iterator(); - } -*/ - //----------------------------------------------------------------------- - /** - * Converts an array of file extensions to suffixes for use - * with IOFileFilters. - * - * @param extensions an array of extensions. Format: {"java", "xml"} - * @return an array of suffixes. Format: {".java", ".xml"} - */ - private static String[] toSuffixes(String[] extensions) { - String[] suffixes = new String[extensions.length]; - for (int i = 0; i < extensions.length; i++) { - suffixes[i] = "." + extensions[i]; - } - return suffixes; - } - - - /** - * Finds files within a given directory (and optionally its subdirectories) - * which match an array of extensions. - * - * @param directory the directory to search in - * @param extensions an array of extensions, ex. {"java","xml"}. If this - * parameter is null, all files are returned. - * @param recursive if true all subdirectories are searched as well - * @return an collection of java.io.File with the matching files - */ - /* - public static Collection listFiles( - File directory, String[] extensions, boolean recursive) { - IOFileFilter filter; - if (extensions == null) { - filter = TrueFileFilter.INSTANCE; - } else { - String[] suffixes = toSuffixes(extensions); - filter = new SuffixFileFilter(suffixes); - } - return listFiles(directory, filter, - recursive ? TrueFileFilter.INSTANCE : FalseFileFilter.INSTANCE); - } -*/ - /** - * Allows iteration over the files in a given directory (and optionally - * its subdirectories) which match an array of extensions. This method - * is based on {@link #listFiles(File, String[], boolean)}, - * which supports Iterable ('foreach' loop). - * - * @param directory the directory to search in - * @param extensions an array of extensions, ex. {"java","xml"}. If this - * parameter is null, all files are returned. - * @param recursive if true all subdirectories are searched as well - * @return an iterator of java.io.File with the matching files - * @since 1.2 - */ - /* - public static Iterator iterateFiles( - File directory, String[] extensions, boolean recursive) { - return listFiles(directory, extensions, recursive).iterator(); - } -*/ - //----------------------------------------------------------------------- - /** - * Compares the contents of two files to determine if they are equal or not. - *

- * This method checks to see if the two files are different lengths - * or if they point to the same file, before resorting to byte-by-byte - * comparison of the contents. - *

- * Code origin: Avalon - * - * @param file1 the first file - * @param file2 the second file - * @return true if the content of the files are equal or they both don't - * exist, false otherwise - * @throws IOException in case of an I/O error - */ - public static boolean contentEquals(File file1, File file2) throws IOException { - boolean file1Exists = file1.exists(); - if (file1Exists != file2.exists()) { - return false; - } - - if (!file1Exists) { - // two not existing files are equal - return true; - } - - if (file1.isDirectory() || file2.isDirectory()) { - // don't want to compare directory contents - throw new IOException("Can't compare directories, only files"); - } - - if (file1.length() != file2.length()) { - // lengths differ, cannot be equal - return false; - } - - if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) { - // same file - return true; - } - - InputStream input1 = null; - InputStream input2 = null; - try { - input1 = new FileInputStream(file1); - input2 = new FileInputStream(file2); - return IOUtils.contentEquals(input1, input2); - - } finally { - IOUtils.closeQuietly(input1); - IOUtils.closeQuietly(input2); - } - } - - //----------------------------------------------------------------------- - /** - * Compares the contents of two files to determine if they are equal or not. - *

- * This method checks to see if the two files point to the same file, - * before resorting to line-by-line comparison of the contents. - *

- * - * @param file1 the first file - * @param file2 the second file - * @param charsetName the character encoding to be used. - * May be null, in which case the platform default is used - * @return true if the content of the files are equal or neither exists, - * false otherwise - * @throws IOException in case of an I/O error - * @since 2.2 - * @see IOUtils#contentEqualsIgnoreEOL(Reader, Reader) - */ - public static boolean contentEqualsIgnoreEOL(File file1, File file2, String charsetName) throws IOException { - boolean file1Exists = file1.exists(); - if (file1Exists != file2.exists()) { - return false; - } - - if (!file1Exists) { - // two not existing files are equal - return true; - } - - if (file1.isDirectory() || file2.isDirectory()) { - // don't want to compare directory contents - throw new IOException("Can't compare directories, only files"); - } - - if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) { - // same file - return true; - } - - Reader input1 = null; - Reader input2 = null; - try { - if (charsetName == null) { - input1 = new InputStreamReader(new FileInputStream(file1)); - input2 = new InputStreamReader(new FileInputStream(file2)); - } else { - input1 = new InputStreamReader(new FileInputStream(file1), charsetName); - input2 = new InputStreamReader(new FileInputStream(file2), charsetName); - } - return IOUtils.contentEqualsIgnoreEOL(input1, input2); - - } finally { - IOUtils.closeQuietly(input1); - IOUtils.closeQuietly(input2); - } - } - - //----------------------------------------------------------------------- - /** - * Convert from a URL to a File. - *

- * From version 1.1 this method will decode the URL. - * Syntax such as file:///my%20docs/file.txt will be - * correctly decoded to /my docs/file.txt. Starting with version - * 1.5, this method uses UTF-8 to decode percent-encoded octets to characters. - * Additionally, malformed percent-encoded octets are handled leniently by - * passing them through literally. - * - * @param url the file URL to convert, null returns null - * @return the equivalent File object, or null - * if the URL's protocol is not file - */ - public static File toFile(URL url) { - if (url == null || !"file".equalsIgnoreCase(url.getProtocol())) { - return null; - } else { - String filename = url.getFile().replace('/', File.separatorChar); - filename = decodeUrl(filename); - return new File(filename); - } - } - - /** - * Decodes the specified URL as per RFC 3986, i.e. transforms - * percent-encoded octets to characters by decoding with the UTF-8 character - * set. This function is primarily intended for usage with - * {@link java.net.URL} which unfortunately does not enforce proper URLs. As - * such, this method will leniently accept invalid characters or malformed - * percent-encoded octets and simply pass them literally through to the - * result string. Except for rare edge cases, this will make unencoded URLs - * pass through unaltered. - * - * @param url The URL to decode, may be null. - * @return The decoded URL or null if the input was - * null. - */ - static String decodeUrl(String url) { - String decoded = url; - if (url != null && url.indexOf('%') >= 0) { - int n = url.length(); - StringBuffer buffer = new StringBuffer(); - ByteBuffer bytes = ByteBuffer.allocate(n); - for (int i = 0; i < n;) { - if (url.charAt(i) == '%') { - try { - do { - byte octet = (byte) Integer.parseInt(url.substring(i + 1, i + 3), 16); - bytes.put(octet); - i += 3; - } while (i < n && url.charAt(i) == '%'); - continue; - } catch (RuntimeException e) { - // malformed percent-encoded octet, fall through and - // append characters literally - } finally { - if (bytes.position() > 0) { - bytes.flip(); - buffer.append(UTF8.decode(bytes).toString()); - bytes.clear(); - } - } - } - buffer.append(url.charAt(i++)); - } - decoded = buffer.toString(); - } - return decoded; - } - - /** - * Converts each of an array of URL to a File. - *

- * Returns an array of the same size as the input. - * If the input is null, an empty array is returned. - * If the input contains null, the output array contains null at the same - * index. - *

- * This method will decode the URL. - * Syntax such as file:///my%20docs/file.txt will be - * correctly decoded to /my docs/file.txt. - * - * @param urls the file URLs to convert, null returns empty array - * @return a non-null array of Files matching the input, with a null item - * if there was a null at that index in the input array - * @throws IllegalArgumentException if any file is not a URL file - * @throws IllegalArgumentException if any file is incorrectly encoded - * @since 1.1 - */ - public static File[] toFiles(URL[] urls) { - if (urls == null || urls.length == 0) { - return EMPTY_FILE_ARRAY; - } - File[] files = new File[urls.length]; - for (int i = 0; i < urls.length; i++) { - URL url = urls[i]; - if (url != null) { - if (url.getProtocol().equals("file") == false) { - throw new IllegalArgumentException( - "URL could not be converted to a File: " + url); - } - files[i] = toFile(url); - } - } - return files; - } - - /** - * Converts each of an array of File to a URL. - *

- * Returns an array of the same size as the input. - * - * @param files the files to convert - * @return an array of URLs matching the input - * @throws IOException if a file cannot be converted - */ - public static URL[] toURLs(File[] files) throws IOException { - URL[] urls = new URL[files.length]; - - for (int i = 0; i < urls.length; i++) { - urls[i] = files[i].toURI().toURL(); - } - - return urls; - } - - //----------------------------------------------------------------------- - /** - * Copies a file to a directory preserving the file date. - *

- * This method copies the contents of the specified source file - * to a file of the same name in the specified destination directory. - * The destination directory is created if it does not exist. - * If the destination file exists, then this method will overwrite it. - *

- * Note: This method tries to preserve the file's last - * modified date/times using {@link File#setLastModified(long)}, however - * it is not guaranteed that the operation will succeed. - * If the modification operation fails, no indication is provided. - * - * @param srcFile an existing file to copy, must not be null - * @param destDir the directory to place the copy in, must not be null - * - * @throws NullPointerException if source or destination is null - * @throws IOException if source or destination is invalid - * @throws IOException if an IO error occurs during copying - * @see #copyFile(File, File, boolean) - */ - public static void copyFileToDirectory(File srcFile, File destDir) throws IOException { - copyFileToDirectory(srcFile, destDir, true); - } - - /** - * Copies a file to a directory optionally preserving the file date. - *

- * This method copies the contents of the specified source file - * to a file of the same name in the specified destination directory. - * The destination directory is created if it does not exist. - * If the destination file exists, then this method will overwrite it. - *

- * Note: Setting preserveFileDate to - * true tries to preserve the file's last modified - * date/times using {@link File#setLastModified(long)}, however it is - * not guaranteed that the operation will succeed. - * If the modification operation fails, no indication is provided. - * - * @param srcFile an existing file to copy, must not be null - * @param destDir the directory to place the copy in, must not be null - * @param preserveFileDate true if the file date of the copy - * should be the same as the original - * - * @throws NullPointerException if source or destination is null - * @throws IOException if source or destination is invalid - * @throws IOException if an IO error occurs during copying - * @see #copyFile(File, File, boolean) - * @since 1.3 - */ - public static void copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate) throws IOException { - if (destDir == null) { - throw new NullPointerException("Destination must not be null"); - } - if (destDir.exists() && destDir.isDirectory() == false) { - throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory"); - } - File destFile = new File(destDir, srcFile.getName()); - copyFile(srcFile, destFile, preserveFileDate); - } - - /** - * Copies a file to a new location preserving the file date. - *

- * This method copies the contents of the specified source file to the - * specified destination file. The directory holding the destination file is - * created if it does not exist. If the destination file exists, then this - * method will overwrite it. - *

- * Note: This method tries to preserve the file's last - * modified date/times using {@link File#setLastModified(long)}, however - * it is not guaranteed that the operation will succeed. - * If the modification operation fails, no indication is provided. - * - * @param srcFile an existing file to copy, must not be null - * @param destFile the new file, must not be null - * - * @throws NullPointerException if source or destination is null - * @throws IOException if source or destination is invalid - * @throws IOException if an IO error occurs during copying - * @see #copyFileToDirectory(File, File) - */ - public static void copyFile(File srcFile, File destFile) throws IOException { - copyFile(srcFile, destFile, true); - } - - /** - * Copies a file to a new location. - *

- * This method copies the contents of the specified source file - * to the specified destination file. - * The directory holding the destination file is created if it does not exist. - * If the destination file exists, then this method will overwrite it. - *

- * Note: Setting preserveFileDate to - * true tries to preserve the file's last modified - * date/times using {@link File#setLastModified(long)}, however it is - * not guaranteed that the operation will succeed. - * If the modification operation fails, no indication is provided. - * - * @param srcFile an existing file to copy, must not be null - * @param destFile the new file, must not be null - * @param preserveFileDate true if the file date of the copy - * should be the same as the original - * - * @throws NullPointerException if source or destination is null - * @throws IOException if source or destination is invalid - * @throws IOException if an IO error occurs during copying - * @see #copyFileToDirectory(File, File, boolean) - */ - public static void copyFile(File srcFile, File destFile, - boolean preserveFileDate) throws IOException { - if (srcFile == null) { - throw new NullPointerException("Source must not be null"); - } - if (destFile == null) { - throw new NullPointerException("Destination must not be null"); - } - if (srcFile.exists() == false) { - throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); - } - if (srcFile.isDirectory()) { - throw new IOException("Source '" + srcFile + "' exists but is a directory"); - } - if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) { - throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same"); - } - File parentFile = destFile.getParentFile(); - if (parentFile != null) { - if (!parentFile.mkdirs() && !parentFile.isDirectory()) { - throw new IOException("Destination '" + parentFile + "' directory cannot be created"); - } - } - if (destFile.exists() && destFile.canWrite() == false) { - throw new IOException("Destination '" + destFile + "' exists but is read-only"); - } - doCopyFile(srcFile, destFile, preserveFileDate); - } - - /** - * Copy bytes from a File to an OutputStream. - *

- * This method buffers the input internally, so there is no need to use a BufferedInputStream. - *

- * - * @param input - * the File to read from - * @param output - * the OutputStream to write to - * @return the number of bytes copied - * @throws NullPointerException - * if the input or output is null - * @throws IOException - * if an I/O error occurs - * @since 2.1 - */ - public static long copyFile(File input, OutputStream output) throws IOException { - final FileInputStream fis = new FileInputStream(input); - try { - return IOUtils.copyLarge(fis, output); - } finally { - fis.close(); - } - } - - /** - * Internal copy file method. - * - * @param srcFile the validated source file, must not be null - * @param destFile the validated destination file, must not be null - * @param preserveFileDate whether to preserve the file date - * @throws IOException if an error occurs - */ - private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { - if (destFile.exists() && destFile.isDirectory()) { - throw new IOException("Destination '" + destFile + "' exists but is a directory"); - } - - FileInputStream fis = null; - FileOutputStream fos = null; - FileChannel input = null; - FileChannel output = null; - try { - fis = new FileInputStream(srcFile); - fos = new FileOutputStream(destFile); - input = fis.getChannel(); - output = fos.getChannel(); - long size = input.size(); - long pos = 0; - long count = 0; - while (pos < size) { - count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos; - pos += output.transferFrom(input, pos, count); - } - } finally { - IOUtils.closeQuietly(output); - IOUtils.closeQuietly(fos); - IOUtils.closeQuietly(input); - IOUtils.closeQuietly(fis); - } - - if (srcFile.length() != destFile.length()) { - throw new IOException("Failed to copy full contents from '" + - srcFile + "' to '" + destFile + "'"); - } - if (preserveFileDate) { - destFile.setLastModified(srcFile.lastModified()); - } - } - - //----------------------------------------------------------------------- - /** - * Copies a directory to within another directory preserving the file dates. - *

- * This method copies the source directory and all its contents to a - * directory of the same name in the specified destination directory. - *

- * The destination directory is created if it does not exist. - * If the destination directory did exist, then this method merges - * the source with the destination, with the source taking precedence. - *

- * Note: This method tries to preserve the files' last - * modified date/times using {@link File#setLastModified(long)}, however - * it is not guaranteed that those operations will succeed. - * If the modification operation fails, no indication is provided. - * - * @param srcDir an existing directory to copy, must not be null - * @param destDir the directory to place the copy in, must not be null - * - * @throws NullPointerException if source or destination is null - * @throws IOException if source or destination is invalid - * @throws IOException if an IO error occurs during copying - * @since 1.2 - */ - public static void copyDirectoryToDirectory(File srcDir, File destDir) throws IOException { - if (srcDir == null) { - throw new NullPointerException("Source must not be null"); - } - if (srcDir.exists() && srcDir.isDirectory() == false) { - throw new IllegalArgumentException("Source '" + destDir + "' is not a directory"); - } - if (destDir == null) { - throw new NullPointerException("Destination must not be null"); - } - if (destDir.exists() && destDir.isDirectory() == false) { - throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory"); - } - copyDirectory(srcDir, new File(destDir, srcDir.getName()), true); - } - - /** - * Copies a whole directory to a new location preserving the file dates. - *

- * This method copies the specified directory and all its child - * directories and files to the specified destination. - * The destination is the new location and name of the directory. - *

- * The destination directory is created if it does not exist. - * If the destination directory did exist, then this method merges - * the source with the destination, with the source taking precedence. - *

- * Note: This method tries to preserve the files' last - * modified date/times using {@link File#setLastModified(long)}, however - * it is not guaranteed that those operations will succeed. - * If the modification operation fails, no indication is provided. - * - * @param srcDir an existing directory to copy, must not be null - * @param destDir the new directory, must not be null - * - * @throws NullPointerException if source or destination is null - * @throws IOException if source or destination is invalid - * @throws IOException if an IO error occurs during copying - * @since 1.1 - */ - public static void copyDirectory(File srcDir, File destDir) throws IOException { - copyDirectory(srcDir, destDir, true); - } - - /** - * Copies a whole directory to a new location. - *

- * This method copies the contents of the specified source directory - * to within the specified destination directory. - *

- * The destination directory is created if it does not exist. - * If the destination directory did exist, then this method merges - * the source with the destination, with the source taking precedence. - *

- * Note: Setting preserveFileDate to - * true tries to preserve the files' last modified - * date/times using {@link File#setLastModified(long)}, however it is - * not guaranteed that those operations will succeed. - * If the modification operation fails, no indication is provided. - * - * @param srcDir an existing directory to copy, must not be null - * @param destDir the new directory, must not be null - * @param preserveFileDate true if the file date of the copy - * should be the same as the original - * - * @throws NullPointerException if source or destination is null - * @throws IOException if source or destination is invalid - * @throws IOException if an IO error occurs during copying - * @since 1.1 - */ - public static void copyDirectory(File srcDir, File destDir, - boolean preserveFileDate) throws IOException { - copyDirectory(srcDir, destDir, null, preserveFileDate); - } - - /** - * Copies a filtered directory to a new location preserving the file dates. - *

- * This method copies the contents of the specified source directory - * to within the specified destination directory. - *

- * The destination directory is created if it does not exist. - * If the destination directory did exist, then this method merges - * the source with the destination, with the source taking precedence. - *

- * Note: This method tries to preserve the files' last - * modified date/times using {@link File#setLastModified(long)}, however - * it is not guaranteed that those operations will succeed. - * If the modification operation fails, no indication is provided. - * - *

Example: Copy directories only

- *
-     *  // only copy the directory structure
-     *  FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY);
-     *  
- * - *

Example: Copy directories and txt files

- *
-     *  // Create a filter for ".txt" files
-     *  IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt");
-     *  IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter);
-     *
-     *  // Create a filter for either directories or ".txt" files
-     *  FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles);
-     *
-     *  // Copy using the filter
-     *  FileUtils.copyDirectory(srcDir, destDir, filter);
-     *  
- * - * @param srcDir an existing directory to copy, must not be null - * @param destDir the new directory, must not be null - * @param filter the filter to apply, null means copy all directories and files - * should be the same as the original - * - * @throws NullPointerException if source or destination is null - * @throws IOException if source or destination is invalid - * @throws IOException if an IO error occurs during copying - * @since 1.4 - */ - public static void copyDirectory(File srcDir, File destDir, - FileFilter filter) throws IOException { - copyDirectory(srcDir, destDir, filter, true); - } - - /** - * Copies a filtered directory to a new location. - *

- * This method copies the contents of the specified source directory - * to within the specified destination directory. - *

- * The destination directory is created if it does not exist. - * If the destination directory did exist, then this method merges - * the source with the destination, with the source taking precedence. - *

- * Note: Setting preserveFileDate to - * true tries to preserve the files' last modified - * date/times using {@link File#setLastModified(long)}, however it is - * not guaranteed that those operations will succeed. - * If the modification operation fails, no indication is provided. - * - *

Example: Copy directories only

- *
-     *  // only copy the directory structure
-     *  FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY, false);
-     *  
- * - *

Example: Copy directories and txt files

- *
-     *  // Create a filter for ".txt" files
-     *  IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt");
-     *  IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter);
-     *
-     *  // Create a filter for either directories or ".txt" files
-     *  FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles);
-     *
-     *  // Copy using the filter
-     *  FileUtils.copyDirectory(srcDir, destDir, filter, false);
-     *  
- * - * @param srcDir an existing directory to copy, must not be null - * @param destDir the new directory, must not be null - * @param filter the filter to apply, null means copy all directories and files - * @param preserveFileDate true if the file date of the copy - * should be the same as the original - * - * @throws NullPointerException if source or destination is null - * @throws IOException if source or destination is invalid - * @throws IOException if an IO error occurs during copying - * @since 1.4 - */ - public static void copyDirectory(File srcDir, File destDir, - FileFilter filter, boolean preserveFileDate) throws IOException { - if (srcDir == null) { - throw new NullPointerException("Source must not be null"); - } - if (destDir == null) { - throw new NullPointerException("Destination must not be null"); - } - if (srcDir.exists() == false) { - throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); - } - if (srcDir.isDirectory() == false) { - throw new IOException("Source '" + srcDir + "' exists but is not a directory"); - } - if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) { - throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same"); - } - - // Cater for destination being directory within the source directory (see IO-141) - List exclusionList = null; - if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { - File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter); - if (srcFiles != null && srcFiles.length > 0) { - exclusionList = new ArrayList(srcFiles.length); - for (File srcFile : srcFiles) { - File copiedFile = new File(destDir, srcFile.getName()); - exclusionList.add(copiedFile.getCanonicalPath()); - } - } - } - doCopyDirectory(srcDir, destDir, filter, preserveFileDate, exclusionList); - } - - /** - * Internal copy directory method. - * - * @param srcDir the validated source directory, must not be null - * @param destDir the validated destination directory, must not be null - * @param filter the filter to apply, null means copy all directories and files - * @param preserveFileDate whether to preserve the file date - * @param exclusionList List of files and directories to exclude from the copy, may be null - * @throws IOException if an error occurs - * @since 1.1 - */ - private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter, - boolean preserveFileDate, List exclusionList) throws IOException { - // recurse - File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter); - if (srcFiles == null) { // null if abstract pathname does not denote a directory, or if an I/O error occurs - throw new IOException("Failed to list contents of " + srcDir); - } - if (destDir.exists()) { - if (destDir.isDirectory() == false) { - throw new IOException("Destination '" + destDir + "' exists but is not a directory"); - } - } else { - if (!destDir.mkdirs() && !destDir.isDirectory()) { - throw new IOException("Destination '" + destDir + "' directory cannot be created"); - } - } - if (destDir.canWrite() == false) { - throw new IOException("Destination '" + destDir + "' cannot be written to"); - } - for (File srcFile : srcFiles) { - File dstFile = new File(destDir, srcFile.getName()); - if (exclusionList == null || !exclusionList.contains(srcFile.getCanonicalPath())) { - if (srcFile.isDirectory()) { - doCopyDirectory(srcFile, dstFile, filter, preserveFileDate, exclusionList); - } else { - doCopyFile(srcFile, dstFile, preserveFileDate); - } - } - } - - // Do this last, as the above has probably affected directory metadata - if (preserveFileDate) { - destDir.setLastModified(srcDir.lastModified()); - } - } - - //----------------------------------------------------------------------- - /** - * Copies bytes from the URL source to a file - * destination. The directories up to destination - * will be created if they don't already exist. destination - * will be overwritten if it already exists. - *

- * Warning: this method does not set a connection or read timeout and thus - * might block forever. Use {@link #copyURLToFile(URL, File, int, int)} - * with reasonable timeouts to prevent this. - * - * @param source the URL to copy bytes from, must not be null - * @param destination the non-directory File to write bytes to - * (possibly overwriting), must not be null - * @throws IOException if source URL cannot be opened - * @throws IOException if destination is a directory - * @throws IOException if destination cannot be written - * @throws IOException if destination needs creating but can't be - * @throws IOException if an IO error occurs during copying - */ - public static void copyURLToFile(URL source, File destination) throws IOException { - InputStream input = source.openStream(); - copyInputStreamToFile(input, destination); - } - - /** - * Copies bytes from the URL source to a file - * destination. The directories up to destination - * will be created if they don't already exist. destination - * will be overwritten if it already exists. - * - * @param source the URL to copy bytes from, must not be null - * @param destination the non-directory File to write bytes to - * (possibly overwriting), must not be null - * @param connectionTimeout the number of milliseconds until this method - * will timeout if no connection could be established to the source - * @param readTimeout the number of milliseconds until this method will - * timeout if no data could be read from the source - * @throws IOException if source URL cannot be opened - * @throws IOException if destination is a directory - * @throws IOException if destination cannot be written - * @throws IOException if destination needs creating but can't be - * @throws IOException if an IO error occurs during copying - * @since 2.0 - */ - public static void copyURLToFile(URL source, File destination, - int connectionTimeout, int readTimeout) throws IOException { - URLConnection connection = source.openConnection(); - connection.setConnectTimeout(connectionTimeout); - connection.setReadTimeout(readTimeout); - InputStream input = connection.getInputStream(); - copyInputStreamToFile(input, destination); - } - - /** - * Copies bytes from an {@link InputStream} source to a file - * destination. The directories up to destination - * will be created if they don't already exist. destination - * will be overwritten if it already exists. - * - * @param source the InputStream to copy bytes from, must not be null - * @param destination the non-directory File to write bytes to - * (possibly overwriting), must not be null - * @throws IOException if destination is a directory - * @throws IOException if destination cannot be written - * @throws IOException if destination needs creating but can't be - * @throws IOException if an IO error occurs during copying - * @since 2.0 - */ - public static void copyInputStreamToFile(InputStream source, File destination) throws IOException { - try { - FileOutputStream output = openOutputStream(destination); - try { - IOUtils.copy(source, output); - output.close(); // don't swallow close Exception if copy completes normally - } finally { - IOUtils.closeQuietly(output); - } - } finally { - IOUtils.closeQuietly(source); - } - } - - //----------------------------------------------------------------------- - /** - * Deletes a directory recursively. - * - * @param directory directory to delete - * @throws IOException in case deletion is unsuccessful - */ - public static void deleteDirectory(File directory) throws IOException { - if (!directory.exists()) { - return; - } - - if (!isSymlink(directory)) { - cleanDirectory(directory); - } - - if (!directory.delete()) { - String message = - "Unable to delete directory " + directory + "."; - throw new IOException(message); - } - } - - /** - * Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories. - *

- * The difference between File.delete() and this method are: - *

    - *
  • A directory to be deleted does not have to be empty.
  • - *
  • No exceptions are thrown when a file or directory cannot be deleted.
  • - *
- * - * @param file file or directory to delete, can be null - * @return true if the file or directory was deleted, otherwise - * false - * - * @since 1.4 - */ - public static boolean deleteQuietly(File file) { - if (file == null) { - return false; - } - try { - if (file.isDirectory()) { - cleanDirectory(file); - } - } catch (Exception ignored) { - } - - try { - return file.delete(); - } catch (Exception ignored) { - return false; - } - } - - /** - * Determines whether the {@code parent} directory contains the {@code child} element (a file or directory). - *

- * Files are normalized before comparison. - *

- * - * Edge cases: - *
    - *
  • A {@code directory} must not be null: if null, throw IllegalArgumentException
  • - *
  • A {@code directory} must be a directory: if not a directory, throw IllegalArgumentException
  • - *
  • A directory does not contain itself: return false
  • - *
  • A null child file is not contained in any parent: return false
  • - *
- * - * @param directory - * the file to consider as the parent. - * @param child - * the file to consider as the child. - * @return true is the candidate leaf is under by the specified composite. False otherwise. - * @throws IOException - * if an IO error occurs while checking the files. - * @since 2.2 - * @see FilenameUtils#directoryContains(String, String) - */ - public static boolean directoryContains(final File directory, final File child) throws IOException { - - // Fail fast against NullPointerException - if (directory == null) { - throw new IllegalArgumentException("Directory must not be null"); - } - - if (!directory.isDirectory()) { - throw new IllegalArgumentException("Not a directory: " + directory); - } - - if (child == null) { - return false; - } - - if (!directory.exists() || !child.exists()) { - return false; - } - - // Canonicalize paths (normalizes relative paths) - String canonicalParent = directory.getCanonicalPath(); - String canonicalChild = child.getCanonicalPath(); - - return FilenameUtils.directoryContains(canonicalParent, canonicalChild); - } - - /** - * Cleans a directory without deleting it. - * - * @param directory directory to clean - * @throws IOException in case cleaning is unsuccessful - */ - public static void cleanDirectory(File directory) throws IOException { - if (!directory.exists()) { - String message = directory + " does not exist"; - throw new IllegalArgumentException(message); - } - - if (!directory.isDirectory()) { - String message = directory + " is not a directory"; - throw new IllegalArgumentException(message); - } - - File[] files = directory.listFiles(); - if (files == null) { // null if security restricted - throw new IOException("Failed to list contents of " + directory); - } - - IOException exception = null; - for (File file : files) { - try { - forceDelete(file); - } catch (IOException ioe) { - exception = ioe; - } - } - - if (null != exception) { - throw exception; - } - } - - //----------------------------------------------------------------------- - /** - * Waits for NFS to propagate a file creation, imposing a timeout. - *

- * This method repeatedly tests {@link File#exists()} until it returns - * true up to the maximum time specified in seconds. - * - * @param file the file to check, must not be null - * @param seconds the maximum time in seconds to wait - * @return true if file exists - * @throws NullPointerException if the file is null - */ - public static boolean waitFor(File file, int seconds) { - int timeout = 0; - int tick = 0; - while (!file.exists()) { - if (tick++ >= 10) { - tick = 0; - if (timeout++ > seconds) { - return false; - } - } - try { - Thread.sleep(100); - } catch (InterruptedException ignore) { - // ignore exception - } catch (Exception ex) { - break; - } - } - return true; - } - - //----------------------------------------------------------------------- - /** - * Reads the contents of a file into a String. - * The file is always closed. - * - * @param file the file to read, must not be null - * @param encoding the encoding to use, null means platform default - * @return the file contents, never null - * @throws IOException in case of an I/O error - * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM - */ - public static String readFileToString(File file, String encoding) throws IOException { - InputStream in = null; - try { - in = openInputStream(file); - return IOUtils.toString(in, encoding); - } finally { - IOUtils.closeQuietly(in); - } - } - - - /** - * Reads the contents of a file into a String using the default encoding for the VM. - * The file is always closed. - * - * @param file the file to read, must not be null - * @return the file contents, never null - * @throws IOException in case of an I/O error - * @since 1.3.1 - */ - public static String readFileToString(File file) throws IOException { - return readFileToString(file, null); - } - - /** - * Reads the contents of a file into a byte array. - * The file is always closed. - * - * @param file the file to read, must not be null - * @return the file contents, never null - * @throws IOException in case of an I/O error - * @since 1.1 - */ - public static byte[] readFileToByteArray(File file) throws IOException { - InputStream in = null; - try { - in = openInputStream(file); - return IOUtils.toByteArray(in, file.length()); - } finally { - IOUtils.closeQuietly(in); - } - } - - /** - * Reads the contents of a file line by line to a List of Strings. - * The file is always closed. - * - * @param file the file to read, must not be null - * @param encoding the encoding to use, null means platform default - * @return the list of Strings representing each line in the file, never null - * @throws IOException in case of an I/O error - * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM - * @since 1.1 - */ - public static List readLines(File file, String encoding) throws IOException { - InputStream in = null; - try { - in = openInputStream(file); - return IOUtils.readLines(in, encoding); - } finally { - IOUtils.closeQuietly(in); - } - } - - /** - * Reads the contents of a file line by line to a List of Strings using the default encoding for the VM. - * The file is always closed. - * - * @param file the file to read, must not be null - * @return the list of Strings representing each line in the file, never null - * @throws IOException in case of an I/O error - * @since 1.3 - */ - public static List readLines(File file) throws IOException { - return readLines(file, null); - } - - /** - * Returns an Iterator for the lines in a File. - *

- * This method opens an InputStream for the file. - * When you have finished with the iterator you should close the stream - * to free internal resources. This can be done by calling the - * {@link LineIterator#close()} or - * {@link LineIterator#closeQuietly(LineIterator)} method. - *

- * The recommended usage pattern is: - *

-     * LineIterator it = FileUtils.lineIterator(file, "UTF-8");
-     * try {
-     *   while (it.hasNext()) {
-     *     String line = it.nextLine();
-     *     /// do something with line
-     *   }
-     * } finally {
-     *   LineIterator.closeQuietly(iterator);
-     * }
-     * 
- *

- * If an exception occurs during the creation of the iterator, the - * underlying stream is closed. - * - * @param file the file to open for input, must not be null - * @param encoding the encoding to use, null means platform default - * @return an Iterator of the lines in the file, never null - * @throws IOException in case of an I/O error (file closed) - * @since 1.2 - */ - public static LineIterator lineIterator(File file, String encoding) throws IOException { - InputStream in = null; - try { - in = openInputStream(file); - return IOUtils.lineIterator(in, encoding); - } catch (IOException ex) { - IOUtils.closeQuietly(in); - throw ex; - } catch (RuntimeException ex) { - IOUtils.closeQuietly(in); - throw ex; - } - } - - /** - * Returns an Iterator for the lines in a File using the default encoding for the VM. - * - * @param file the file to open for input, must not be null - * @return an Iterator of the lines in the file, never null - * @throws IOException in case of an I/O error (file closed) - * @since 1.3 - * @see #lineIterator(File, String) - */ - public static LineIterator lineIterator(File file) throws IOException { - return lineIterator(file, null); - } - - //----------------------------------------------------------------------- - /** - * Writes a String to a file creating the file if it does not exist. - * - * NOTE: As from v1.3, the parent directories of the file will be created - * if they do not exist. - * - * @param file the file to write - * @param data the content to write to the file - * @param encoding the encoding to use, null means platform default - * @throws IOException in case of an I/O error - * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM - */ - public static void writeStringToFile(File file, String data, String encoding) throws IOException { - writeStringToFile(file, data, encoding, false); - } - - /** - * Writes a String to a file creating the file if it does not exist. - * - * @param file the file to write - * @param data the content to write to the file - * @param encoding the encoding to use, null means platform default - * @param append if true, then the String will be added to the - * end of the file rather than overwriting - * @throws IOException in case of an I/O error - * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM - * @since 2.1 - */ - public static void writeStringToFile(File file, String data, String encoding, boolean append) throws IOException { - OutputStream out = null; - try { - out = openOutputStream(file, append); - IOUtils.write(data, out, encoding); - out.close(); // don't swallow close Exception if copy completes normally - } finally { - IOUtils.closeQuietly(out); - } - } - - /** - * Writes a String to a file creating the file if it does not exist using the default encoding for the VM. - * - * @param file the file to write - * @param data the content to write to the file - * @throws IOException in case of an I/O error - */ - public static void writeStringToFile(File file, String data) throws IOException { - writeStringToFile(file, data, null, false); - } - - /** - * Writes a String to a file creating the file if it does not exist using the default encoding for the VM. - * - * @param file the file to write - * @param data the content to write to the file - * @param append if true, then the String will be added to the - * end of the file rather than overwriting - * @throws IOException in case of an I/O error - * @since 2.1 - */ - public static void writeStringToFile(File file, String data, boolean append) throws IOException { - writeStringToFile(file, data, null, append); - } - - /** - * Writes a CharSequence to a file creating the file if it does not exist using the default encoding for the VM. - * - * @param file the file to write - * @param data the content to write to the file - * @throws IOException in case of an I/O error - * @since 2.0 - */ - public static void write(File file, CharSequence data) throws IOException { - write(file, data, null, false); - } - - /** - * Writes a CharSequence to a file creating the file if it does not exist using the default encoding for the VM. - * - * @param file the file to write - * @param data the content to write to the file - * @param append if true, then the data will be added to the - * end of the file rather than overwriting - * @throws IOException in case of an I/O error - * @since 2.1 - */ - public static void write(File file, CharSequence data, boolean append) throws IOException { - write(file, data, null, append); - } - - /** - * Writes a CharSequence to a file creating the file if it does not exist. - * - * @param file the file to write - * @param data the content to write to the file - * @param encoding the encoding to use, null means platform default - * @throws IOException in case of an I/O error - * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM - * @since 2.0 - */ - public static void write(File file, CharSequence data, String encoding) throws IOException { - write(file, data, encoding, false); - } - - /** - * Writes a CharSequence to a file creating the file if it does not exist. - * - * @param file the file to write - * @param data the content to write to the file - * @param encoding the encoding to use, null means platform default - * @param append if true, then the data will be added to the - * end of the file rather than overwriting - * @throws IOException in case of an I/O error - * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM - * @since IO 2.1 - */ - public static void write(File file, CharSequence data, String encoding, boolean append) throws IOException { - String str = data == null ? null : data.toString(); - writeStringToFile(file, str, encoding, append); - } - - /** - * Writes a byte array to a file creating the file if it does not exist. - *

- * NOTE: As from v1.3, the parent directories of the file will be created - * if they do not exist. - * - * @param file the file to write to - * @param data the content to write to the file - * @throws IOException in case of an I/O error - * @since 1.1 - */ - public static void writeByteArrayToFile(File file, byte[] data) throws IOException { - writeByteArrayToFile(file, data, false); - } - - /** - * Writes a byte array to a file creating the file if it does not exist. - * - * @param file the file to write to - * @param data the content to write to the file - * @param append if true, then bytes will be added to the - * end of the file rather than overwriting - * @throws IOException in case of an I/O error - * @since IO 2.1 - */ - public static void writeByteArrayToFile(File file, byte[] data, boolean append) throws IOException { - OutputStream out = null; - try { - out = openOutputStream(file, append); - out.write(data); - out.close(); // don't swallow close Exception if copy completes normally - } finally { - IOUtils.closeQuietly(out); - } - } - - /** - * Writes the toString() value of each item in a collection to - * the specified File line by line. - * The specified character encoding and the default line ending will be used. - *

- * NOTE: As from v1.3, the parent directories of the file will be created - * if they do not exist. - * - * @param file the file to write to - * @param encoding the encoding to use, null means platform default - * @param lines the lines to write, null entries produce blank lines - * @throws IOException in case of an I/O error - * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM - * @since 1.1 - */ - public static void writeLines(File file, String encoding, Collection lines) throws IOException { - writeLines(file, encoding, lines, null, false); - } - - /** - * Writes the toString() value of each item in a collection to - * the specified File line by line, optionally appending. - * The specified character encoding and the default line ending will be used. - * - * @param file the file to write to - * @param encoding the encoding to use, null means platform default - * @param lines the lines to write, null entries produce blank lines - * @param append if true, then the lines will be added to the - * end of the file rather than overwriting - * @throws IOException in case of an I/O error - * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM - * @since 2.1 - */ - public static void writeLines(File file, String encoding, Collection lines, boolean append) throws IOException { - writeLines(file, encoding, lines, null, append); - } - - /** - * Writes the toString() value of each item in a collection to - * the specified File line by line. - * The default VM encoding and the default line ending will be used. - * - * @param file the file to write to - * @param lines the lines to write, null entries produce blank lines - * @throws IOException in case of an I/O error - * @since 1.3 - */ - public static void writeLines(File file, Collection lines) throws IOException { - writeLines(file, null, lines, null, false); - } - - /** - * Writes the toString() value of each item in a collection to - * the specified File line by line. - * The default VM encoding and the default line ending will be used. - * - * @param file the file to write to - * @param lines the lines to write, null entries produce blank lines - * @param append if true, then the lines will be added to the - * end of the file rather than overwriting - * @throws IOException in case of an I/O error - * @since 2.1 - */ - public static void writeLines(File file, Collection lines, boolean append) throws IOException { - writeLines(file, null, lines, null, append); - } - - /** - * Writes the toString() value of each item in a collection to - * the specified File line by line. - * The specified character encoding and the line ending will be used. - *

- * NOTE: As from v1.3, the parent directories of the file will be created - * if they do not exist. - * - * @param file the file to write to - * @param encoding the encoding to use, null means platform default - * @param lines the lines to write, null entries produce blank lines - * @param lineEnding the line separator to use, null is system default - * @throws IOException in case of an I/O error - * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM - * @since 1.1 - */ - public static void writeLines(File file, String encoding, Collection lines, String lineEnding) - throws IOException { - writeLines(file, encoding, lines, lineEnding, false); - } - - /** - * Writes the toString() value of each item in a collection to - * the specified File line by line. - * The specified character encoding and the line ending will be used. - * - * @param file the file to write to - * @param encoding the encoding to use, null means platform default - * @param lines the lines to write, null entries produce blank lines - * @param lineEnding the line separator to use, null is system default - * @param append if true, then the lines will be added to the - * end of the file rather than overwriting - * @throws IOException in case of an I/O error - * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM - * @since 2.1 - */ - public static void writeLines(File file, String encoding, Collection lines, String lineEnding, boolean append) - throws IOException { - OutputStream out = null; - try { - out = openOutputStream(file, append); - IOUtils.writeLines(lines, lineEnding, out, encoding); - out.close(); // don't swallow close Exception if copy completes normally - } finally { - IOUtils.closeQuietly(out); - } - } - - /** - * Writes the toString() value of each item in a collection to - * the specified File line by line. - * The default VM encoding and the specified line ending will be used. - * - * @param file the file to write to - * @param lines the lines to write, null entries produce blank lines - * @param lineEnding the line separator to use, null is system default - * @throws IOException in case of an I/O error - * @since 1.3 - */ - public static void writeLines(File file, Collection lines, String lineEnding) throws IOException { - writeLines(file, null, lines, lineEnding, false); - } - - /** - * Writes the toString() value of each item in a collection to - * the specified File line by line. - * The default VM encoding and the specified line ending will be used. - * - * @param file the file to write to - * @param lines the lines to write, null entries produce blank lines - * @param lineEnding the line separator to use, null is system default - * @param append if true, then the lines will be added to the - * end of the file rather than overwriting - * @throws IOException in case of an I/O error - * @since 2.1 - */ - public static void writeLines(File file, Collection lines, String lineEnding, boolean append) - throws IOException { - writeLines(file, null, lines, lineEnding, append); - } - - //----------------------------------------------------------------------- - /** - * Deletes a file. If file is a directory, delete it and all sub-directories. - *

- * The difference between File.delete() and this method are: - *

    - *
  • A directory to be deleted does not have to be empty.
  • - *
  • You get exceptions when a file or directory cannot be deleted. - * (java.io.File methods returns a boolean)
  • - *
- * - * @param file file or directory to delete, must not be null - * @throws NullPointerException if the directory is null - * @throws FileNotFoundException if the file was not found - * @throws IOException in case deletion is unsuccessful - */ - public static void forceDelete(File file) throws IOException { - if (file.isDirectory()) { - deleteDirectory(file); - } else { - boolean filePresent = file.exists(); - if (!file.delete()) { - if (!filePresent){ - throw new FileNotFoundException("File does not exist: " + file); - } - String message = - "Unable to delete file: " + file; - throw new IOException(message); - } - } - } - - /** - * Schedules a file to be deleted when JVM exits. - * If file is directory delete it and all sub-directories. - * - * @param file file or directory to delete, must not be null - * @throws NullPointerException if the file is null - * @throws IOException in case deletion is unsuccessful - */ - public static void forceDeleteOnExit(File file) throws IOException { - if (file.isDirectory()) { - deleteDirectoryOnExit(file); - } else { - file.deleteOnExit(); - } - } - - /** - * Schedules a directory recursively for deletion on JVM exit. - * - * @param directory directory to delete, must not be null - * @throws NullPointerException if the directory is null - * @throws IOException in case deletion is unsuccessful - */ - private static void deleteDirectoryOnExit(File directory) throws IOException { - if (!directory.exists()) { - return; - } - - directory.deleteOnExit(); - if (!isSymlink(directory)) { - cleanDirectoryOnExit(directory); - } - } - - /** - * Cleans a directory without deleting it. - * - * @param directory directory to clean, must not be null - * @throws NullPointerException if the directory is null - * @throws IOException in case cleaning is unsuccessful - */ - private static void cleanDirectoryOnExit(File directory) throws IOException { - if (!directory.exists()) { - String message = directory + " does not exist"; - throw new IllegalArgumentException(message); - } - - if (!directory.isDirectory()) { - String message = directory + " is not a directory"; - throw new IllegalArgumentException(message); - } - - File[] files = directory.listFiles(); - if (files == null) { // null if security restricted - throw new IOException("Failed to list contents of " + directory); - } - - IOException exception = null; - for (File file : files) { - try { - forceDeleteOnExit(file); - } catch (IOException ioe) { - exception = ioe; - } - } - - if (null != exception) { - throw exception; - } - } - - /** - * Makes a directory, including any necessary but nonexistent parent - * directories. If a file already exists with specified name but it is - * not a directory then an IOException is thrown. - * If the directory cannot be created (or does not already exist) - * then an IOException is thrown. - * - * @param directory directory to create, must not be null - * @throws NullPointerException if the directory is null - * @throws IOException if the directory cannot be created or the file already exists but is not a directory - */ - public static void forceMkdir(File directory) throws IOException { - if (directory.exists()) { - if (!directory.isDirectory()) { - String message = - "File " - + directory - + " exists and is " - + "not a directory. Unable to create directory."; - throw new IOException(message); - } - } else { - if (!directory.mkdirs()) { - // Double-check that some other thread or process hasn't made - // the directory in the background - if (!directory.isDirectory()) - { - String message = - "Unable to create directory " + directory; - throw new IOException(message); - } - } - } - } - - //----------------------------------------------------------------------- - /** - * Returns the size of the specified file or directory. If the provided - * {@link File} is a regular file, then the file's length is returned. - * If the argument is a directory, then the size of the directory is - * calculated recursively. If a directory or subdirectory is security - * restricted, its size will not be included. - * - * @param file the regular file or directory to return the size - * of (must not be null). - * - * @return the length of the file, or recursive size of the directory, - * provided (in bytes). - * - * @throws NullPointerException if the file is null - * @throws IllegalArgumentException if the file does not exist. - * - * @since 2.0 - */ - public static long sizeOf(File file) { - - if (!file.exists()) { - String message = file + " does not exist"; - throw new IllegalArgumentException(message); - } - - if (file.isDirectory()) { - return sizeOfDirectory(file); - } else { - return file.length(); - } - - } - - /** - * Counts the size of a directory recursively (sum of the length of all files). - * - * @param directory directory to inspect, must not be null - * @return size of directory in bytes, 0 if directory is security restricted - * @throws NullPointerException if the directory is null - */ - public static long sizeOfDirectory(File directory) { - if (!directory.exists()) { - String message = directory + " does not exist"; - throw new IllegalArgumentException(message); - } - - if (!directory.isDirectory()) { - String message = directory + " is not a directory"; - throw new IllegalArgumentException(message); - } - - long size = 0; - - File[] files = directory.listFiles(); - if (files == null) { // null if security restricted - return 0L; - } - for (File file : files) { - size += sizeOf(file); - } - - return size; - } - - //----------------------------------------------------------------------- - /** - * Tests if the specified File is newer than the reference - * File. - * - * @param file the File of which the modification date must - * be compared, must not be null - * @param reference the File of which the modification date - * is used, must not be null - * @return true if the File exists and has been modified more - * recently than the reference File - * @throws IllegalArgumentException if the file is null - * @throws IllegalArgumentException if the reference file is null or doesn't exist - */ - public static boolean isFileNewer(File file, File reference) { - if (reference == null) { - throw new IllegalArgumentException("No specified reference file"); - } - if (!reference.exists()) { - throw new IllegalArgumentException("The reference file '" - + reference + "' doesn't exist"); - } - return isFileNewer(file, reference.lastModified()); - } - - /** - * Tests if the specified File is newer than the specified - * Date. - * - * @param file the File of which the modification date - * must be compared, must not be null - * @param date the date reference, must not be null - * @return true if the File exists and has been modified - * after the given Date. - * @throws IllegalArgumentException if the file is null - * @throws IllegalArgumentException if the date is null - */ - public static boolean isFileNewer(File file, Date date) { - if (date == null) { - throw new IllegalArgumentException("No specified date"); - } - return isFileNewer(file, date.getTime()); - } - - /** - * Tests if the specified File is newer than the specified - * time reference. - * - * @param file the File of which the modification date must - * be compared, must not be null - * @param timeMillis the time reference measured in milliseconds since the - * epoch (00:00:00 GMT, January 1, 1970) - * @return true if the File exists and has been modified after - * the given time reference. - * @throws IllegalArgumentException if the file is null - */ - public static boolean isFileNewer(File file, long timeMillis) { - if (file == null) { - throw new IllegalArgumentException("No specified file"); - } - if (!file.exists()) { - return false; - } - return file.lastModified() > timeMillis; - } - - - //----------------------------------------------------------------------- - /** - * Tests if the specified File is older than the reference - * File. - * - * @param file the File of which the modification date must - * be compared, must not be null - * @param reference the File of which the modification date - * is used, must not be null - * @return true if the File exists and has been modified before - * the reference File - * @throws IllegalArgumentException if the file is null - * @throws IllegalArgumentException if the reference file is null or doesn't exist - */ - public static boolean isFileOlder(File file, File reference) { - if (reference == null) { - throw new IllegalArgumentException("No specified reference file"); - } - if (!reference.exists()) { - throw new IllegalArgumentException("The reference file '" - + reference + "' doesn't exist"); - } - return isFileOlder(file, reference.lastModified()); - } - - /** - * Tests if the specified File is older than the specified - * Date. - * - * @param file the File of which the modification date - * must be compared, must not be null - * @param date the date reference, must not be null - * @return true if the File exists and has been modified - * before the given Date. - * @throws IllegalArgumentException if the file is null - * @throws IllegalArgumentException if the date is null - */ - public static boolean isFileOlder(File file, Date date) { - if (date == null) { - throw new IllegalArgumentException("No specified date"); - } - return isFileOlder(file, date.getTime()); - } - - /** - * Tests if the specified File is older than the specified - * time reference. - * - * @param file the File of which the modification date must - * be compared, must not be null - * @param timeMillis the time reference measured in milliseconds since the - * epoch (00:00:00 GMT, January 1, 1970) - * @return true if the File exists and has been modified before - * the given time reference. - * @throws IllegalArgumentException if the file is null - */ - public static boolean isFileOlder(File file, long timeMillis) { - if (file == null) { - throw new IllegalArgumentException("No specified file"); - } - if (!file.exists()) { - return false; - } - return file.lastModified() < timeMillis; - } - - //----------------------------------------------------------------------- - /** - * Computes the checksum of a file using the CRC32 checksum routine. - * The value of the checksum is returned. - * - * @param file the file to checksum, must not be null - * @return the checksum value - * @throws NullPointerException if the file or checksum is null - * @throws IllegalArgumentException if the file is a directory - * @throws IOException if an IO error occurs reading the file - * @since 1.3 - */ - public static long checksumCRC32(File file) throws IOException { - CRC32 crc = new CRC32(); - checksum(file, crc); - return crc.getValue(); - } - - /** - * Computes the checksum of a file using the specified checksum object. - * Multiple files may be checked using one Checksum instance - * if desired simply by reusing the same checksum object. - * For example: - *
-     *   long csum = FileUtils.checksum(file, new CRC32()).getValue();
-     * 
- * - * @param file the file to checksum, must not be null - * @param checksum the checksum object to be used, must not be null - * @return the checksum specified, updated with the content of the file - * @throws NullPointerException if the file or checksum is null - * @throws IllegalArgumentException if the file is a directory - * @throws IOException if an IO error occurs reading the file - * @since 1.3 - */ - public static Checksum checksum(File file, Checksum checksum) throws IOException { - if (file.isDirectory()) { - throw new IllegalArgumentException("Checksums can't be computed on directories"); - } - InputStream in = null; - try { - in = new CheckedInputStream(new FileInputStream(file), checksum); - IOUtils.copy(in, new NullOutputStream()); - } finally { - IOUtils.closeQuietly(in); - } - return checksum; - } - - /** - * Moves a directory. - *

- * When the destination directory is on another file system, do a "copy and delete". - * - * @param srcDir the directory to be moved - * @param destDir the destination directory - * @throws NullPointerException if source or destination is null - * @throws FileExistsException if the destination directory exists - * @throws IOException if source or destination is invalid - * @throws IOException if an IO error occurs moving the file - * @since 1.4 - */ - public static void moveDirectory(File srcDir, File destDir) throws IOException { - if (srcDir == null) { - throw new NullPointerException("Source must not be null"); - } - if (destDir == null) { - throw new NullPointerException("Destination must not be null"); - } - if (!srcDir.exists()) { - throw new FileNotFoundException("Source '" + srcDir + "' does not exist"); - } - if (!srcDir.isDirectory()) { - throw new IOException("Source '" + srcDir + "' is not a directory"); - } - if (destDir.exists()) { - throw new FileExistsException("Destination '" + destDir + "' already exists"); - } - boolean rename = srcDir.renameTo(destDir); - if (!rename) { - if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) { - throw new IOException("Cannot move directory: "+srcDir+" to a subdirectory of itself: "+destDir); - } - copyDirectory( srcDir, destDir ); - deleteDirectory( srcDir ); - if (srcDir.exists()) { - throw new IOException("Failed to delete original directory '" + srcDir + - "' after copy to '" + destDir + "'"); - } - } - } - - /** - * Moves a directory to another directory. - * - * @param src the file to be moved - * @param destDir the destination file - * @param createDestDir If true create the destination directory, - * otherwise if false throw an IOException - * @throws NullPointerException if source or destination is null - * @throws FileExistsException if the directory exists in the destination directory - * @throws IOException if source or destination is invalid - * @throws IOException if an IO error occurs moving the file - * @since 1.4 - */ - public static void moveDirectoryToDirectory(File src, File destDir, boolean createDestDir) throws IOException { - if (src == null) { - throw new NullPointerException("Source must not be null"); - } - if (destDir == null) { - throw new NullPointerException("Destination directory must not be null"); - } - if (!destDir.exists() && createDestDir) { - destDir.mkdirs(); - } - if (!destDir.exists()) { - throw new FileNotFoundException("Destination directory '" + destDir + - "' does not exist [createDestDir=" + createDestDir +"]"); - } - if (!destDir.isDirectory()) { - throw new IOException("Destination '" + destDir + "' is not a directory"); - } - moveDirectory(src, new File(destDir, src.getName())); - - } - - /** - * Moves a file. - *

- * When the destination file is on another file system, do a "copy and delete". - * - * @param srcFile the file to be moved - * @param destFile the destination file - * @throws NullPointerException if source or destination is null - * @throws FileExistsException if the destination file exists - * @throws IOException if source or destination is invalid - * @throws IOException if an IO error occurs moving the file - * @since 1.4 - */ - public static void moveFile(File srcFile, File destFile) throws IOException { - if (srcFile == null) { - throw new NullPointerException("Source must not be null"); - } - if (destFile == null) { - throw new NullPointerException("Destination must not be null"); - } - if (!srcFile.exists()) { - throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); - } - if (srcFile.isDirectory()) { - throw new IOException("Source '" + srcFile + "' is a directory"); - } - if (destFile.exists()) { - throw new FileExistsException("Destination '" + destFile + "' already exists"); - } - if (destFile.isDirectory()) { - throw new IOException("Destination '" + destFile + "' is a directory"); - } - boolean rename = srcFile.renameTo(destFile); - if (!rename) { - copyFile( srcFile, destFile ); - if (!srcFile.delete()) { - FileUtils.deleteQuietly(destFile); - throw new IOException("Failed to delete original file '" + srcFile + - "' after copy to '" + destFile + "'"); - } - } - } - - /** - * Moves a file to a directory. - * - * @param srcFile the file to be moved - * @param destDir the destination file - * @param createDestDir If true create the destination directory, - * otherwise if false throw an IOException - * @throws NullPointerException if source or destination is null - * @throws FileExistsException if the destination file exists - * @throws IOException if source or destination is invalid - * @throws IOException if an IO error occurs moving the file - * @since 1.4 - */ - public static void moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) throws IOException { - if (srcFile == null) { - throw new NullPointerException("Source must not be null"); - } - if (destDir == null) { - throw new NullPointerException("Destination directory must not be null"); - } - if (!destDir.exists() && createDestDir) { - destDir.mkdirs(); - } - if (!destDir.exists()) { - throw new FileNotFoundException("Destination directory '" + destDir + - "' does not exist [createDestDir=" + createDestDir +"]"); - } - if (!destDir.isDirectory()) { - throw new IOException("Destination '" + destDir + "' is not a directory"); - } - moveFile(srcFile, new File(destDir, srcFile.getName())); - } - - /** - * Moves a file or directory to the destination directory. - *

- * When the destination is on another file system, do a "copy and delete". - * - * @param src the file or directory to be moved - * @param destDir the destination directory - * @param createDestDir If true create the destination directory, - * otherwise if false throw an IOException - * @throws NullPointerException if source or destination is null - * @throws FileExistsException if the directory or file exists in the destination directory - * @throws IOException if source or destination is invalid - * @throws IOException if an IO error occurs moving the file - * @since 1.4 - */ - public static void moveToDirectory(File src, File destDir, boolean createDestDir) throws IOException { - if (src == null) { - throw new NullPointerException("Source must not be null"); - } - if (destDir == null) { - throw new NullPointerException("Destination must not be null"); - } - if (!src.exists()) { - throw new FileNotFoundException("Source '" + src + "' does not exist"); - } - if (src.isDirectory()) { - moveDirectoryToDirectory(src, destDir, createDestDir); - } else { - moveFileToDirectory(src, destDir, createDestDir); - } - } - - /** - * Determines whether the specified file is a Symbolic Link rather than an actual file. - *

- * Will not return true if there is a Symbolic Link anywhere in the path, - * only if the specific file is. - *

- * Note: the current implementation always returns {@code false} if the system - * is detected as Windows using {@link FilenameUtils#isSystemWindows()} - * - * @param file the file to check - * @return true if the file is a Symbolic Link - * @throws IOException if an IO error occurs while checking the file - * @since 2.0 - */ - public static boolean isSymlink(File file) throws IOException { - if (file == null) { - throw new NullPointerException("File must not be null"); - } - if (FilenameUtils.isSystemWindows()) { - return false; - } - File fileInCanonicalDir = null; - if (file.getParent() == null) { - fileInCanonicalDir = file; - } else { - File canonicalDir = file.getParentFile().getCanonicalFile(); - fileInCanonicalDir = new File(canonicalDir, file.getName()); - } - - if (fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile())) { - return false; - } else { - return true; - } - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/FilenameUtils.java b/apacheandroid/src/main/java/org/apache/commons/io/FilenameUtils.java deleted file mode 100644 index 48a3ded51..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/FilenameUtils.java +++ /dev/null @@ -1,1401 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Stack; - -/** - * General filename and filepath manipulation utilities. - *

- * When dealing with filenames you can hit problems when moving from a Windows - * based development machine to a Unix based production machine. - * This class aims to help avoid those problems. - *

- * NOTE: You may be able to avoid using this class entirely simply by - * using JDK {@link java.io.File File} objects and the two argument constructor - * {@link java.io.File#File(java.io.File, java.lang.String) File(File,String)}. - *

- * Most methods on this class are designed to work the same on both Unix and Windows. - * Those that don't include 'System', 'Unix' or 'Windows' in their name. - *

- * Most methods recognise both separators (forward and back), and both - * sets of prefixes. See the javadoc of each method for details. - *

- * This class defines six components within a filename - * (example C:\dev\project\file.txt): - *

    - *
  • the prefix - C:\
  • - *
  • the path - dev\project\
  • - *
  • the full path - C:\dev\project\
  • - *
  • the name - file.txt
  • - *
  • the base name - file
  • - *
  • the extension - txt
  • - *
- * Note that this class works best if directory filenames end with a separator. - * If you omit the last separator, it is impossible to determine if the filename - * corresponds to a file or a directory. As a result, we have chosen to say - * it corresponds to a file. - *

- * This class only supports Unix and Windows style names. - * Prefixes are matched as follows: - *

- * Windows:
- * a\b\c.txt           --> ""          --> relative
- * \a\b\c.txt          --> "\"         --> current drive absolute
- * C:a\b\c.txt         --> "C:"        --> drive relative
- * C:\a\b\c.txt        --> "C:\"       --> absolute
- * \\server\a\b\c.txt  --> "\\server\" --> UNC
- *
- * Unix:
- * a/b/c.txt           --> ""          --> relative
- * /a/b/c.txt          --> "/"         --> absolute
- * ~/a/b/c.txt         --> "~/"        --> current user
- * ~                   --> "~/"        --> current user (slash added)
- * ~user/a/b/c.txt     --> "~user/"    --> named user
- * ~user               --> "~user/"    --> named user (slash added)
- * 
- * Both prefix styles are matched always, irrespective of the machine that you are - * currently running on. - *

- * Origin of code: Excalibur, Alexandria, Tomcat, Commons-Utils. - * - * @version $Id: FilenameUtils.java 1304052 2012-03-22 20:55:29Z ggregory $ - * @since 1.1 - */ -public class FilenameUtils { - - /** - * The extension separator character. - * @since 1.4 - */ - public static final char EXTENSION_SEPARATOR = '.'; - - /** - * The extension separator String. - * @since 1.4 - */ - public static final String EXTENSION_SEPARATOR_STR = Character.toString(EXTENSION_SEPARATOR); - - /** - * The Unix separator character. - */ - private static final char UNIX_SEPARATOR = '/'; - - /** - * The Windows separator character. - */ - private static final char WINDOWS_SEPARATOR = '\\'; - - /** - * The system separator character. - */ - private static final char SYSTEM_SEPARATOR = File.separatorChar; - - /** - * The separator character that is the opposite of the system separator. - */ - private static final char OTHER_SEPARATOR; - static { - if (isSystemWindows()) { - OTHER_SEPARATOR = UNIX_SEPARATOR; - } else { - OTHER_SEPARATOR = WINDOWS_SEPARATOR; - } - } - - /** - * Instances should NOT be constructed in standard programming. - */ - public FilenameUtils() { - super(); - } - - //----------------------------------------------------------------------- - /** - * Determines if Windows file system is in use. - * - * @return true if the system is Windows - */ - static boolean isSystemWindows() { - return SYSTEM_SEPARATOR == WINDOWS_SEPARATOR; - } - - //----------------------------------------------------------------------- - /** - * Checks if the character is a separator. - * - * @param ch the character to check - * @return true if it is a separator character - */ - private static boolean isSeparator(char ch) { - return ch == UNIX_SEPARATOR || ch == WINDOWS_SEPARATOR; - } - - //----------------------------------------------------------------------- - /** - * Normalizes a path, removing double and single dot path steps. - *

- * This method normalizes a path to a standard format. - * The input may contain separators in either Unix or Windows format. - * The output will contain separators in the format of the system. - *

- * A trailing slash will be retained. - * A double slash will be merged to a single slash (but UNC names are handled). - * A single dot path segment will be removed. - * A double dot will cause that path segment and the one before to be removed. - * If the double dot has no parent path segment to work with, null - * is returned. - *

- * The output will be the same on both Unix and Windows except - * for the separator character. - *

-     * /foo//               -->   /foo/
-     * /foo/./              -->   /foo/
-     * /foo/../bar          -->   /bar
-     * /foo/../bar/         -->   /bar/
-     * /foo/../bar/../baz   -->   /baz
-     * //foo//./bar         -->   /foo/bar
-     * /../                 -->   null
-     * ../foo               -->   null
-     * foo/bar/..           -->   foo/
-     * foo/../../bar        -->   null
-     * foo/../bar           -->   bar
-     * //server/foo/../bar  -->   //server/bar
-     * //server/../bar      -->   null
-     * C:\foo\..\bar        -->   C:\bar
-     * C:\..\bar            -->   null
-     * ~/foo/../bar/        -->   ~/bar/
-     * ~/../bar             -->   null
-     * 
- * (Note the file separator returned will be correct for Windows/Unix) - * - * @param filename the filename to normalize, null returns null - * @return the normalized filename, or null if invalid - */ - public static String normalize(String filename) { - return doNormalize(filename, SYSTEM_SEPARATOR, true); - } - /** - * Normalizes a path, removing double and single dot path steps. - *

- * This method normalizes a path to a standard format. - * The input may contain separators in either Unix or Windows format. - * The output will contain separators in the format specified. - *

- * A trailing slash will be retained. - * A double slash will be merged to a single slash (but UNC names are handled). - * A single dot path segment will be removed. - * A double dot will cause that path segment and the one before to be removed. - * If the double dot has no parent path segment to work with, null - * is returned. - *

- * The output will be the same on both Unix and Windows except - * for the separator character. - *

-     * /foo//               -->   /foo/
-     * /foo/./              -->   /foo/
-     * /foo/../bar          -->   /bar
-     * /foo/../bar/         -->   /bar/
-     * /foo/../bar/../baz   -->   /baz
-     * //foo//./bar         -->   /foo/bar
-     * /../                 -->   null
-     * ../foo               -->   null
-     * foo/bar/..           -->   foo/
-     * foo/../../bar        -->   null
-     * foo/../bar           -->   bar
-     * //server/foo/../bar  -->   //server/bar
-     * //server/../bar      -->   null
-     * C:\foo\..\bar        -->   C:\bar
-     * C:\..\bar            -->   null
-     * ~/foo/../bar/        -->   ~/bar/
-     * ~/../bar             -->   null
-     * 
- * The output will be the same on both Unix and Windows including - * the separator character. - * - * @param filename the filename to normalize, null returns null - * @param unixSeparator true if a unix separator should - * be used or false if a windows separator should be used. - * @return the normalized filename, or null if invalid - * @since 2.0 - */ - public static String normalize(String filename, boolean unixSeparator) { - char separator = unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR; - return doNormalize(filename, separator, true); - } - - //----------------------------------------------------------------------- - /** - * Normalizes a path, removing double and single dot path steps, - * and removing any final directory separator. - *

- * This method normalizes a path to a standard format. - * The input may contain separators in either Unix or Windows format. - * The output will contain separators in the format of the system. - *

- * A trailing slash will be removed. - * A double slash will be merged to a single slash (but UNC names are handled). - * A single dot path segment will be removed. - * A double dot will cause that path segment and the one before to be removed. - * If the double dot has no parent path segment to work with, null - * is returned. - *

- * The output will be the same on both Unix and Windows except - * for the separator character. - *

-     * /foo//               -->   /foo
-     * /foo/./              -->   /foo
-     * /foo/../bar          -->   /bar
-     * /foo/../bar/         -->   /bar
-     * /foo/../bar/../baz   -->   /baz
-     * //foo//./bar         -->   /foo/bar
-     * /../                 -->   null
-     * ../foo               -->   null
-     * foo/bar/..           -->   foo
-     * foo/../../bar        -->   null
-     * foo/../bar           -->   bar
-     * //server/foo/../bar  -->   //server/bar
-     * //server/../bar      -->   null
-     * C:\foo\..\bar        -->   C:\bar
-     * C:\..\bar            -->   null
-     * ~/foo/../bar/        -->   ~/bar
-     * ~/../bar             -->   null
-     * 
- * (Note the file separator returned will be correct for Windows/Unix) - * - * @param filename the filename to normalize, null returns null - * @return the normalized filename, or null if invalid - */ - public static String normalizeNoEndSeparator(String filename) { - return doNormalize(filename, SYSTEM_SEPARATOR, false); - } - - /** - * Normalizes a path, removing double and single dot path steps, - * and removing any final directory separator. - *

- * This method normalizes a path to a standard format. - * The input may contain separators in either Unix or Windows format. - * The output will contain separators in the format specified. - *

- * A trailing slash will be removed. - * A double slash will be merged to a single slash (but UNC names are handled). - * A single dot path segment will be removed. - * A double dot will cause that path segment and the one before to be removed. - * If the double dot has no parent path segment to work with, null - * is returned. - *

- * The output will be the same on both Unix and Windows including - * the separator character. - *

-     * /foo//               -->   /foo
-     * /foo/./              -->   /foo
-     * /foo/../bar          -->   /bar
-     * /foo/../bar/         -->   /bar
-     * /foo/../bar/../baz   -->   /baz
-     * //foo//./bar         -->   /foo/bar
-     * /../                 -->   null
-     * ../foo               -->   null
-     * foo/bar/..           -->   foo
-     * foo/../../bar        -->   null
-     * foo/../bar           -->   bar
-     * //server/foo/../bar  -->   //server/bar
-     * //server/../bar      -->   null
-     * C:\foo\..\bar        -->   C:\bar
-     * C:\..\bar            -->   null
-     * ~/foo/../bar/        -->   ~/bar
-     * ~/../bar             -->   null
-     * 
- * - * @param filename the filename to normalize, null returns null - * @param unixSeparator true if a unix separator should - * be used or false if a windows separtor should be used. - * @return the normalized filename, or null if invalid - * @since 2.0 - */ - public static String normalizeNoEndSeparator(String filename, boolean unixSeparator) { - char separator = unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR; - return doNormalize(filename, separator, false); - } - - /** - * Internal method to perform the normalization. - * - * @param filename the filename - * @param separator The separator character to use - * @param keepSeparator true to keep the final separator - * @return the normalized filename - */ - private static String doNormalize(String filename, char separator, boolean keepSeparator) { - if (filename == null) { - return null; - } - int size = filename.length(); - if (size == 0) { - return filename; - } - int prefix = getPrefixLength(filename); - if (prefix < 0) { - return null; - } - - char[] array = new char[size + 2]; // +1 for possible extra slash, +2 for arraycopy - filename.getChars(0, filename.length(), array, 0); - - // fix separators throughout - char otherSeparator = separator == SYSTEM_SEPARATOR ? OTHER_SEPARATOR : SYSTEM_SEPARATOR; - for (int i = 0; i < array.length; i++) { - if (array[i] == otherSeparator) { - array[i] = separator; - } - } - - // add extra separator on the end to simplify code below - boolean lastIsDirectory = true; - if (array[size - 1] != separator) { - array[size++] = separator; - lastIsDirectory = false; - } - - // adjoining slashes - for (int i = prefix + 1; i < size; i++) { - if (array[i] == separator && array[i - 1] == separator) { - System.arraycopy(array, i, array, i - 1, size - i); - size--; - i--; - } - } - - // dot slash - for (int i = prefix + 1; i < size; i++) { - if (array[i] == separator && array[i - 1] == '.' && - (i == prefix + 1 || array[i - 2] == separator)) { - if (i == size - 1) { - lastIsDirectory = true; - } - System.arraycopy(array, i + 1, array, i - 1, size - i); - size -=2; - i--; - } - } - - // double dot slash - outer: - for (int i = prefix + 2; i < size; i++) { - if (array[i] == separator && array[i - 1] == '.' && array[i - 2] == '.' && - (i == prefix + 2 || array[i - 3] == separator)) { - if (i == prefix + 2) { - return null; - } - if (i == size - 1) { - lastIsDirectory = true; - } - int j; - for (j = i - 4 ; j >= prefix; j--) { - if (array[j] == separator) { - // remove b/../ from a/b/../c - System.arraycopy(array, i + 1, array, j + 1, size - i); - size -= i - j; - i = j + 1; - continue outer; - } - } - // remove a/../ from a/../c - System.arraycopy(array, i + 1, array, prefix, size - i); - size -= i + 1 - prefix; - i = prefix + 1; - } - } - - if (size <= 0) { // should never be less than 0 - return ""; - } - if (size <= prefix) { // should never be less than prefix - return new String(array, 0, size); - } - if (lastIsDirectory && keepSeparator) { - return new String(array, 0, size); // keep trailing separator - } - return new String(array, 0, size - 1); // lose trailing separator - } - - //----------------------------------------------------------------------- - /** - * Concatenates a filename to a base path using normal command line style rules. - *

- * The effect is equivalent to resultant directory after changing - * directory to the first argument, followed by changing directory to - * the second argument. - *

- * The first argument is the base path, the second is the path to concatenate. - * The returned path is always normalized via {@link #normalize(String)}, - * thus .. is handled. - *

- * If pathToAdd is absolute (has an absolute prefix), then - * it will be normalized and returned. - * Otherwise, the paths will be joined, normalized and returned. - *

- * The output will be the same on both Unix and Windows except - * for the separator character. - *

-     * /foo/ + bar          -->   /foo/bar
-     * /foo + bar           -->   /foo/bar
-     * /foo + /bar          -->   /bar
-     * /foo + C:/bar        -->   C:/bar
-     * /foo + C:bar         -->   C:bar (*)
-     * /foo/a/ + ../bar     -->   foo/bar
-     * /foo/ + ../../bar    -->   null
-     * /foo/ + /bar         -->   /bar
-     * /foo/.. + /bar       -->   /bar
-     * /foo + bar/c.txt     -->   /foo/bar/c.txt
-     * /foo/c.txt + bar     -->   /foo/c.txt/bar (!)
-     * 
- * (*) Note that the Windows relative drive prefix is unreliable when - * used with this method. - * (!) Note that the first parameter must be a path. If it ends with a name, then - * the name will be built into the concatenated path. If this might be a problem, - * use {@link #getFullPath(String)} on the base path argument. - * - * @param basePath the base path to attach to, always treated as a path - * @param fullFilenameToAdd the filename (or path) to attach to the base - * @return the concatenated path, or null if invalid - */ - public static String concat(String basePath, String fullFilenameToAdd) { - int prefix = getPrefixLength(fullFilenameToAdd); - if (prefix < 0) { - return null; - } - if (prefix > 0) { - return normalize(fullFilenameToAdd); - } - if (basePath == null) { - return null; - } - int len = basePath.length(); - if (len == 0) { - return normalize(fullFilenameToAdd); - } - char ch = basePath.charAt(len - 1); - if (isSeparator(ch)) { - return normalize(basePath + fullFilenameToAdd); - } else { - return normalize(basePath + '/' + fullFilenameToAdd); - } - } - - /** - * Determines whether the {@code parent} directory contains the {@code child} element (a file or directory). - *

- * The files names are expected to be normalized. - *

- * - * Edge cases: - *
    - *
  • A {@code directory} must not be null: if null, throw IllegalArgumentException
  • - *
  • A directory does not contain itself: return false
  • - *
  • A null child file is not contained in any parent: return false
  • - *
- * - * @param canonicalParent - * the file to consider as the parent. - * @param canonicalChild - * the file to consider as the child. - * @return true is the candidate leaf is under by the specified composite. False otherwise. - * @throws IOException - * if an IO error occurs while checking the files. - * @since 2.2 - * @see FileUtils#directoryContains(File, File) - */ - public static boolean directoryContains(final String canonicalParent, final String canonicalChild) - throws IOException { - - // Fail fast against NullPointerException - if (canonicalParent == null) { - throw new IllegalArgumentException("Directory must not be null"); - } - - if (canonicalChild == null) { - return false; - } - - if (IOCase.SYSTEM.checkEquals(canonicalParent, canonicalChild)) { - return false; - } - - return IOCase.SYSTEM.checkStartsWith(canonicalChild, canonicalParent); - } - - //----------------------------------------------------------------------- - /** - * Converts all separators to the Unix separator of forward slash. - * - * @param path the path to be changed, null ignored - * @return the updated path - */ - public static String separatorsToUnix(String path) { - if (path == null || path.indexOf(WINDOWS_SEPARATOR) == -1) { - return path; - } - return path.replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR); - } - - /** - * Converts all separators to the Windows separator of backslash. - * - * @param path the path to be changed, null ignored - * @return the updated path - */ - public static String separatorsToWindows(String path) { - if (path == null || path.indexOf(UNIX_SEPARATOR) == -1) { - return path; - } - return path.replace(UNIX_SEPARATOR, WINDOWS_SEPARATOR); - } - - /** - * Converts all separators to the system separator. - * - * @param path the path to be changed, null ignored - * @return the updated path - */ - public static String separatorsToSystem(String path) { - if (path == null) { - return null; - } - if (isSystemWindows()) { - return separatorsToWindows(path); - } else { - return separatorsToUnix(path); - } - } - - //----------------------------------------------------------------------- - /** - * Returns the length of the filename prefix, such as C:/ or ~/. - *

- * This method will handle a file in either Unix or Windows format. - *

- * The prefix length includes the first slash in the full filename - * if applicable. Thus, it is possible that the length returned is greater - * than the length of the input string. - *

-     * Windows:
-     * a\b\c.txt           --> ""          --> relative
-     * \a\b\c.txt          --> "\"         --> current drive absolute
-     * C:a\b\c.txt         --> "C:"        --> drive relative
-     * C:\a\b\c.txt        --> "C:\"       --> absolute
-     * \\server\a\b\c.txt  --> "\\server\" --> UNC
-     *
-     * Unix:
-     * a/b/c.txt           --> ""          --> relative
-     * /a/b/c.txt          --> "/"         --> absolute
-     * ~/a/b/c.txt         --> "~/"        --> current user
-     * ~                   --> "~/"        --> current user (slash added)
-     * ~user/a/b/c.txt     --> "~user/"    --> named user
-     * ~user               --> "~user/"    --> named user (slash added)
-     * 
- *

- * The output will be the same irrespective of the machine that the code is running on. - * ie. both Unix and Windows prefixes are matched regardless. - * - * @param filename the filename to find the prefix in, null returns -1 - * @return the length of the prefix, -1 if invalid or null - */ - public static int getPrefixLength(String filename) { - if (filename == null) { - return -1; - } - int len = filename.length(); - if (len == 0) { - return 0; - } - char ch0 = filename.charAt(0); - if (ch0 == ':') { - return -1; - } - if (len == 1) { - if (ch0 == '~') { - return 2; // return a length greater than the input - } - return isSeparator(ch0) ? 1 : 0; - } else { - if (ch0 == '~') { - int posUnix = filename.indexOf(UNIX_SEPARATOR, 1); - int posWin = filename.indexOf(WINDOWS_SEPARATOR, 1); - if (posUnix == -1 && posWin == -1) { - return len + 1; // return a length greater than the input - } - posUnix = posUnix == -1 ? posWin : posUnix; - posWin = posWin == -1 ? posUnix : posWin; - return Math.min(posUnix, posWin) + 1; - } - char ch1 = filename.charAt(1); - if (ch1 == ':') { - ch0 = Character.toUpperCase(ch0); - if (ch0 >= 'A' && ch0 <= 'Z') { - if (len == 2 || isSeparator(filename.charAt(2)) == false) { - return 2; - } - return 3; - } - return -1; - - } else if (isSeparator(ch0) && isSeparator(ch1)) { - int posUnix = filename.indexOf(UNIX_SEPARATOR, 2); - int posWin = filename.indexOf(WINDOWS_SEPARATOR, 2); - if (posUnix == -1 && posWin == -1 || posUnix == 2 || posWin == 2) { - return -1; - } - posUnix = posUnix == -1 ? posWin : posUnix; - posWin = posWin == -1 ? posUnix : posWin; - return Math.min(posUnix, posWin) + 1; - } else { - return isSeparator(ch0) ? 1 : 0; - } - } - } - - /** - * Returns the index of the last directory separator character. - *

- * This method will handle a file in either Unix or Windows format. - * The position of the last forward or backslash is returned. - *

- * The output will be the same irrespective of the machine that the code is running on. - * - * @param filename the filename to find the last path separator in, null returns -1 - * @return the index of the last separator character, or -1 if there - * is no such character - */ - public static int indexOfLastSeparator(String filename) { - if (filename == null) { - return -1; - } - int lastUnixPos = filename.lastIndexOf(UNIX_SEPARATOR); - int lastWindowsPos = filename.lastIndexOf(WINDOWS_SEPARATOR); - return Math.max(lastUnixPos, lastWindowsPos); - } - - /** - * Returns the index of the last extension separator character, which is a dot. - *

- * This method also checks that there is no directory separator after the last dot. - * To do this it uses {@link #indexOfLastSeparator(String)} which will - * handle a file in either Unix or Windows format. - *

- * The output will be the same irrespective of the machine that the code is running on. - * - * @param filename the filename to find the last path separator in, null returns -1 - * @return the index of the last separator character, or -1 if there - * is no such character - */ - public static int indexOfExtension(String filename) { - if (filename == null) { - return -1; - } - int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR); - int lastSeparator = indexOfLastSeparator(filename); - return lastSeparator > extensionPos ? -1 : extensionPos; - } - - //----------------------------------------------------------------------- - /** - * Gets the prefix from a full filename, such as C:/ - * or ~/. - *

- * This method will handle a file in either Unix or Windows format. - * The prefix includes the first slash in the full filename where applicable. - *

-     * Windows:
-     * a\b\c.txt           --> ""          --> relative
-     * \a\b\c.txt          --> "\"         --> current drive absolute
-     * C:a\b\c.txt         --> "C:"        --> drive relative
-     * C:\a\b\c.txt        --> "C:\"       --> absolute
-     * \\server\a\b\c.txt  --> "\\server\" --> UNC
-     *
-     * Unix:
-     * a/b/c.txt           --> ""          --> relative
-     * /a/b/c.txt          --> "/"         --> absolute
-     * ~/a/b/c.txt         --> "~/"        --> current user
-     * ~                   --> "~/"        --> current user (slash added)
-     * ~user/a/b/c.txt     --> "~user/"    --> named user
-     * ~user               --> "~user/"    --> named user (slash added)
-     * 
- *

- * The output will be the same irrespective of the machine that the code is running on. - * ie. both Unix and Windows prefixes are matched regardless. - * - * @param filename the filename to query, null returns null - * @return the prefix of the file, null if invalid - */ - public static String getPrefix(String filename) { - if (filename == null) { - return null; - } - int len = getPrefixLength(filename); - if (len < 0) { - return null; - } - if (len > filename.length()) { - return filename + UNIX_SEPARATOR; // we know this only happens for unix - } - return filename.substring(0, len); - } - - /** - * Gets the path from a full filename, which excludes the prefix. - *

- * This method will handle a file in either Unix or Windows format. - * The method is entirely text based, and returns the text before and - * including the last forward or backslash. - *

-     * C:\a\b\c.txt --> a\b\
-     * ~/a/b/c.txt  --> a/b/
-     * a.txt        --> ""
-     * a/b/c        --> a/b/
-     * a/b/c/       --> a/b/c/
-     * 
- *

- * The output will be the same irrespective of the machine that the code is running on. - *

- * This method drops the prefix from the result. - * See {@link #getFullPath(String)} for the method that retains the prefix. - * - * @param filename the filename to query, null returns null - * @return the path of the file, an empty string if none exists, null if invalid - */ - public static String getPath(String filename) { - return doGetPath(filename, 1); - } - - /** - * Gets the path from a full filename, which excludes the prefix, and - * also excluding the final directory separator. - *

- * This method will handle a file in either Unix or Windows format. - * The method is entirely text based, and returns the text before the - * last forward or backslash. - *

-     * C:\a\b\c.txt --> a\b
-     * ~/a/b/c.txt  --> a/b
-     * a.txt        --> ""
-     * a/b/c        --> a/b
-     * a/b/c/       --> a/b/c
-     * 
- *

- * The output will be the same irrespective of the machine that the code is running on. - *

- * This method drops the prefix from the result. - * See {@link #getFullPathNoEndSeparator(String)} for the method that retains the prefix. - * - * @param filename the filename to query, null returns null - * @return the path of the file, an empty string if none exists, null if invalid - */ - public static String getPathNoEndSeparator(String filename) { - return doGetPath(filename, 0); - } - - /** - * Does the work of getting the path. - * - * @param filename the filename - * @param separatorAdd 0 to omit the end separator, 1 to return it - * @return the path - */ - private static String doGetPath(String filename, int separatorAdd) { - if (filename == null) { - return null; - } - int prefix = getPrefixLength(filename); - if (prefix < 0) { - return null; - } - int index = indexOfLastSeparator(filename); - int endIndex = index+separatorAdd; - if (prefix >= filename.length() || index < 0 || prefix >= endIndex) { - return ""; - } - return filename.substring(prefix, endIndex); - } - - /** - * Gets the full path from a full filename, which is the prefix + path. - *

- * This method will handle a file in either Unix or Windows format. - * The method is entirely text based, and returns the text before and - * including the last forward or backslash. - *

-     * C:\a\b\c.txt --> C:\a\b\
-     * ~/a/b/c.txt  --> ~/a/b/
-     * a.txt        --> ""
-     * a/b/c        --> a/b/
-     * a/b/c/       --> a/b/c/
-     * C:           --> C:
-     * C:\          --> C:\
-     * ~            --> ~/
-     * ~/           --> ~/
-     * ~user        --> ~user/
-     * ~user/       --> ~user/
-     * 
- *

- * The output will be the same irrespective of the machine that the code is running on. - * - * @param filename the filename to query, null returns null - * @return the path of the file, an empty string if none exists, null if invalid - */ - public static String getFullPath(String filename) { - return doGetFullPath(filename, true); - } - - /** - * Gets the full path from a full filename, which is the prefix + path, - * and also excluding the final directory separator. - *

- * This method will handle a file in either Unix or Windows format. - * The method is entirely text based, and returns the text before the - * last forward or backslash. - *

-     * C:\a\b\c.txt --> C:\a\b
-     * ~/a/b/c.txt  --> ~/a/b
-     * a.txt        --> ""
-     * a/b/c        --> a/b
-     * a/b/c/       --> a/b/c
-     * C:           --> C:
-     * C:\          --> C:\
-     * ~            --> ~
-     * ~/           --> ~
-     * ~user        --> ~user
-     * ~user/       --> ~user
-     * 
- *

- * The output will be the same irrespective of the machine that the code is running on. - * - * @param filename the filename to query, null returns null - * @return the path of the file, an empty string if none exists, null if invalid - */ - public static String getFullPathNoEndSeparator(String filename) { - return doGetFullPath(filename, false); - } - - /** - * Does the work of getting the path. - * - * @param filename the filename - * @param includeSeparator true to include the end separator - * @return the path - */ - private static String doGetFullPath(String filename, boolean includeSeparator) { - if (filename == null) { - return null; - } - int prefix = getPrefixLength(filename); - if (prefix < 0) { - return null; - } - if (prefix >= filename.length()) { - if (includeSeparator) { - return getPrefix(filename); // add end slash if necessary - } else { - return filename; - } - } - int index = indexOfLastSeparator(filename); - if (index < 0) { - return filename.substring(0, prefix); - } - int end = index + (includeSeparator ? 1 : 0); - if (end == 0) { - end++; - } - return filename.substring(0, end); - } - - /** - * Gets the name minus the path from a full filename. - *

- * This method will handle a file in either Unix or Windows format. - * The text after the last forward or backslash is returned. - *

-     * a/b/c.txt --> c.txt
-     * a.txt     --> a.txt
-     * a/b/c     --> c
-     * a/b/c/    --> ""
-     * 
- *

- * The output will be the same irrespective of the machine that the code is running on. - * - * @param filename the filename to query, null returns null - * @return the name of the file without the path, or an empty string if none exists - */ - public static String getName(String filename) { - if (filename == null) { - return null; - } - int index = indexOfLastSeparator(filename); - return filename.substring(index + 1); - } - - /** - * Gets the base name, minus the full path and extension, from a full filename. - *

- * This method will handle a file in either Unix or Windows format. - * The text after the last forward or backslash and before the last dot is returned. - *

-     * a/b/c.txt --> c
-     * a.txt     --> a
-     * a/b/c     --> c
-     * a/b/c/    --> ""
-     * 
- *

- * The output will be the same irrespective of the machine that the code is running on. - * - * @param filename the filename to query, null returns null - * @return the name of the file without the path, or an empty string if none exists - */ - public static String getBaseName(String filename) { - return removeExtension(getName(filename)); - } - - /** - * Gets the extension of a filename. - *

- * This method returns the textual part of the filename after the last dot. - * There must be no directory separator after the dot. - *

-     * foo.txt      --> "txt"
-     * a/b/c.jpg    --> "jpg"
-     * a/b.txt/c    --> ""
-     * a/b/c        --> ""
-     * 
- *

- * The output will be the same irrespective of the machine that the code is running on. - * - * @param filename the filename to retrieve the extension of. - * @return the extension of the file or an empty string if none exists or null - * if the filename is null. - */ - public static String getExtension(String filename) { - if (filename == null) { - return null; - } - int index = indexOfExtension(filename); - if (index == -1) { - return ""; - } else { - return filename.substring(index + 1); - } - } - - //----------------------------------------------------------------------- - /** - * Removes the extension from a filename. - *

- * This method returns the textual part of the filename before the last dot. - * There must be no directory separator after the dot. - *

-     * foo.txt    --> foo
-     * a\b\c.jpg  --> a\b\c
-     * a\b\c      --> a\b\c
-     * a.b\c      --> a.b\c
-     * 
- *

- * The output will be the same irrespective of the machine that the code is running on. - * - * @param filename the filename to query, null returns null - * @return the filename minus the extension - */ - public static String removeExtension(String filename) { - if (filename == null) { - return null; - } - int index = indexOfExtension(filename); - if (index == -1) { - return filename; - } else { - return filename.substring(0, index); - } - } - - //----------------------------------------------------------------------- - /** - * Checks whether two filenames are equal exactly. - *

- * No processing is performed on the filenames other than comparison, - * thus this is merely a null-safe case-sensitive equals. - * - * @param filename1 the first filename to query, may be null - * @param filename2 the second filename to query, may be null - * @return true if the filenames are equal, null equals null - * @see IOCase#SENSITIVE - */ - public static boolean equals(String filename1, String filename2) { - return equals(filename1, filename2, false, IOCase.SENSITIVE); - } - - /** - * Checks whether two filenames are equal using the case rules of the system. - *

- * No processing is performed on the filenames other than comparison. - * The check is case-sensitive on Unix and case-insensitive on Windows. - * - * @param filename1 the first filename to query, may be null - * @param filename2 the second filename to query, may be null - * @return true if the filenames are equal, null equals null - * @see IOCase#SYSTEM - */ - public static boolean equalsOnSystem(String filename1, String filename2) { - return equals(filename1, filename2, false, IOCase.SYSTEM); - } - - //----------------------------------------------------------------------- - /** - * Checks whether two filenames are equal after both have been normalized. - *

- * Both filenames are first passed to {@link #normalize(String)}. - * The check is then performed in a case-sensitive manner. - * - * @param filename1 the first filename to query, may be null - * @param filename2 the second filename to query, may be null - * @return true if the filenames are equal, null equals null - * @see IOCase#SENSITIVE - */ - public static boolean equalsNormalized(String filename1, String filename2) { - return equals(filename1, filename2, true, IOCase.SENSITIVE); - } - - /** - * Checks whether two filenames are equal after both have been normalized - * and using the case rules of the system. - *

- * Both filenames are first passed to {@link #normalize(String)}. - * The check is then performed case-sensitive on Unix and - * case-insensitive on Windows. - * - * @param filename1 the first filename to query, may be null - * @param filename2 the second filename to query, may be null - * @return true if the filenames are equal, null equals null - * @see IOCase#SYSTEM - */ - public static boolean equalsNormalizedOnSystem(String filename1, String filename2) { - return equals(filename1, filename2, true, IOCase.SYSTEM); - } - - /** - * Checks whether two filenames are equal, optionally normalizing and providing - * control over the case-sensitivity. - * - * @param filename1 the first filename to query, may be null - * @param filename2 the second filename to query, may be null - * @param normalized whether to normalize the filenames - * @param caseSensitivity what case sensitivity rule to use, null means case-sensitive - * @return true if the filenames are equal, null equals null - * @since 1.3 - */ - public static boolean equals( - String filename1, String filename2, - boolean normalized, IOCase caseSensitivity) { - - if (filename1 == null || filename2 == null) { - return filename1 == null && filename2 == null; - } - if (normalized) { - filename1 = normalize(filename1); - filename2 = normalize(filename2); - if (filename1 == null || filename2 == null) { - throw new NullPointerException( - "Error normalizing one or both of the file names"); - } - } - if (caseSensitivity == null) { - caseSensitivity = IOCase.SENSITIVE; - } - return caseSensitivity.checkEquals(filename1, filename2); - } - - //----------------------------------------------------------------------- - /** - * Checks whether the extension of the filename is that specified. - *

- * This method obtains the extension as the textual part of the filename - * after the last dot. There must be no directory separator after the dot. - * The extension check is case-sensitive on all platforms. - * - * @param filename the filename to query, null returns false - * @param extension the extension to check for, null or empty checks for no extension - * @return true if the filename has the specified extension - */ - public static boolean isExtension(String filename, String extension) { - if (filename == null) { - return false; - } - if (extension == null || extension.length() == 0) { - return indexOfExtension(filename) == -1; - } - String fileExt = getExtension(filename); - return fileExt.equals(extension); - } - - /** - * Checks whether the extension of the filename is one of those specified. - *

- * This method obtains the extension as the textual part of the filename - * after the last dot. There must be no directory separator after the dot. - * The extension check is case-sensitive on all platforms. - * - * @param filename the filename to query, null returns false - * @param extensions the extensions to check for, null checks for no extension - * @return true if the filename is one of the extensions - */ - public static boolean isExtension(String filename, String[] extensions) { - if (filename == null) { - return false; - } - if (extensions == null || extensions.length == 0) { - return indexOfExtension(filename) == -1; - } - String fileExt = getExtension(filename); - for (String extension : extensions) { - if (fileExt.equals(extension)) { - return true; - } - } - return false; - } - - /** - * Checks whether the extension of the filename is one of those specified. - *

- * This method obtains the extension as the textual part of the filename - * after the last dot. There must be no directory separator after the dot. - * The extension check is case-sensitive on all platforms. - * - * @param filename the filename to query, null returns false - * @param extensions the extensions to check for, null checks for no extension - * @return true if the filename is one of the extensions - */ - public static boolean isExtension(String filename, Collection extensions) { - if (filename == null) { - return false; - } - if (extensions == null || extensions.isEmpty()) { - return indexOfExtension(filename) == -1; - } - String fileExt = getExtension(filename); - for (String extension : extensions) { - if (fileExt.equals(extension)) { - return true; - } - } - return false; - } - - //----------------------------------------------------------------------- - /** - * Checks a filename to see if it matches the specified wildcard matcher, - * always testing case-sensitive. - *

- * The wildcard matcher uses the characters '?' and '*' to represent a - * single or multiple (zero or more) wildcard characters. - * This is the same as often found on Dos/Unix command lines. - * The check is case-sensitive always. - *

-     * wildcardMatch("c.txt", "*.txt")      --> true
-     * wildcardMatch("c.txt", "*.jpg")      --> false
-     * wildcardMatch("a/b/c.txt", "a/b/*")  --> true
-     * wildcardMatch("c.txt", "*.???")      --> true
-     * wildcardMatch("c.txt", "*.????")     --> false
-     * 
- * N.B. the sequence "*?" does not work properly at present in match strings. - * - * @param filename the filename to match on - * @param wildcardMatcher the wildcard string to match against - * @return true if the filename matches the wilcard string - * @see IOCase#SENSITIVE - */ - public static boolean wildcardMatch(String filename, String wildcardMatcher) { - return wildcardMatch(filename, wildcardMatcher, IOCase.SENSITIVE); - } - - /** - * Checks a filename to see if it matches the specified wildcard matcher - * using the case rules of the system. - *

- * The wildcard matcher uses the characters '?' and '*' to represent a - * single or multiple (zero or more) wildcard characters. - * This is the same as often found on Dos/Unix command lines. - * The check is case-sensitive on Unix and case-insensitive on Windows. - *

-     * wildcardMatch("c.txt", "*.txt")      --> true
-     * wildcardMatch("c.txt", "*.jpg")      --> false
-     * wildcardMatch("a/b/c.txt", "a/b/*")  --> true
-     * wildcardMatch("c.txt", "*.???")      --> true
-     * wildcardMatch("c.txt", "*.????")     --> false
-     * 
- * N.B. the sequence "*?" does not work properly at present in match strings. - * - * @param filename the filename to match on - * @param wildcardMatcher the wildcard string to match against - * @return true if the filename matches the wilcard string - * @see IOCase#SYSTEM - */ - public static boolean wildcardMatchOnSystem(String filename, String wildcardMatcher) { - return wildcardMatch(filename, wildcardMatcher, IOCase.SYSTEM); - } - - /** - * Checks a filename to see if it matches the specified wildcard matcher - * allowing control over case-sensitivity. - *

- * The wildcard matcher uses the characters '?' and '*' to represent a - * single or multiple (zero or more) wildcard characters. - * N.B. the sequence "*?" does not work properly at present in match strings. - * - * @param filename the filename to match on - * @param wildcardMatcher the wildcard string to match against - * @param caseSensitivity what case sensitivity rule to use, null means case-sensitive - * @return true if the filename matches the wilcard string - * @since 1.3 - */ - public static boolean wildcardMatch(String filename, String wildcardMatcher, IOCase caseSensitivity) { - if (filename == null && wildcardMatcher == null) { - return true; - } - if (filename == null || wildcardMatcher == null) { - return false; - } - if (caseSensitivity == null) { - caseSensitivity = IOCase.SENSITIVE; - } - String[] wcs = splitOnTokens(wildcardMatcher); - boolean anyChars = false; - int textIdx = 0; - int wcsIdx = 0; - Stack backtrack = new Stack(); - - // loop around a backtrack stack, to handle complex * matching - do { - if (backtrack.size() > 0) { - int[] array = backtrack.pop(); - wcsIdx = array[0]; - textIdx = array[1]; - anyChars = true; - } - - // loop whilst tokens and text left to process - while (wcsIdx < wcs.length) { - - if (wcs[wcsIdx].equals("?")) { - // ? so move to next text char - textIdx++; - if (textIdx > filename.length()) { - break; - } - anyChars = false; - - } else if (wcs[wcsIdx].equals("*")) { - // set any chars status - anyChars = true; - if (wcsIdx == wcs.length - 1) { - textIdx = filename.length(); - } - - } else { - // matching text token - if (anyChars) { - // any chars then try to locate text token - textIdx = caseSensitivity.checkIndexOf(filename, textIdx, wcs[wcsIdx]); - if (textIdx == -1) { - // token not found - break; - } - int repeat = caseSensitivity.checkIndexOf(filename, textIdx + 1, wcs[wcsIdx]); - if (repeat >= 0) { - backtrack.push(new int[] {wcsIdx, repeat}); - } - } else { - // matching from current position - if (!caseSensitivity.checkRegionMatches(filename, textIdx, wcs[wcsIdx])) { - // couldnt match token - break; - } - } - - // matched text token, move text index to end of matched token - textIdx += wcs[wcsIdx].length(); - anyChars = false; - } - - wcsIdx++; - } - - // full match - if (wcsIdx == wcs.length && textIdx == filename.length()) { - return true; - } - - } while (backtrack.size() > 0); - - return false; - } - - /** - * Splits a string into a number of tokens. - * The text is split by '?' and '*'. - * Where multiple '*' occur consecutively they are collapsed into a single '*'. - * - * @param text the text to split - * @return the array of tokens, never null - */ - static String[] splitOnTokens(String text) { - // used by wildcardMatch - // package level so a unit test may run on this - - if (text.indexOf('?') == -1 && text.indexOf('*') == -1) { - return new String[] { text }; - } - - char[] array = text.toCharArray(); - ArrayList list = new ArrayList(); - StringBuilder buffer = new StringBuilder(); - for (int i = 0; i < array.length; i++) { - if (array[i] == '?' || array[i] == '*') { - if (buffer.length() != 0) { - list.add(buffer.toString()); - buffer.setLength(0); - } - if (array[i] == '?') { - list.add("?"); - } else if (list.isEmpty() || - i > 0 && list.get(list.size() - 1).equals("*") == false) { - list.add("*"); - } - } else { - buffer.append(array[i]); - } - } - if (buffer.length() != 0) { - list.add(buffer.toString()); - } - - return list.toArray( new String[ list.size() ] ); - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/IOCase.java b/apacheandroid/src/main/java/org/apache/commons/io/IOCase.java deleted file mode 100644 index cefa6a236..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/IOCase.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io; - -import java.io.Serializable; - -/** - * Enumeration of IO case sensitivity. - *

- * Different filing systems have different rules for case-sensitivity. - * Windows is case-insensitive, Unix is case-sensitive. - *

- * This class captures that difference, providing an enumeration to - * control how filename comparisons should be performed. It also provides - * methods that use the enumeration to perform comparisons. - *

- * Wherever possible, you should use the check methods in this - * class to compare filenames. - * - * @version $Id: IOCase.java 1304052 2012-03-22 20:55:29Z ggregory $ - * @since 1.3 - */ -public final class IOCase implements Serializable { - - /** - * The constant for case sensitive regardless of operating system. - */ - public static final IOCase SENSITIVE = new IOCase("Sensitive", true); - - /** - * The constant for case insensitive regardless of operating system. - */ - public static final IOCase INSENSITIVE = new IOCase("Insensitive", false); - - /** - * The constant for case sensitivity determined by the current operating system. - * Windows is case-insensitive when comparing filenames, Unix is case-sensitive. - *

- * Note: This only caters for Windows and Unix. Other operating - * systems (e.g. OSX and OpenVMS) are treated as case sensitive if they use the - * Unix file separator and case-insensitive if they use the Windows file separator - * (see {@link java.io.File#separatorChar}). - *

- * If you derialize this constant of Windows, and deserialize on Unix, or vice - * versa, then the value of the case-sensitivity flag will change. - */ - public static final IOCase SYSTEM = new IOCase("System", !FilenameUtils.isSystemWindows()); - - /** Serialization version. */ - private static final long serialVersionUID = -6343169151696340687L; - - /** The enumeration name. */ - private final String name; - - /** The sensitivity flag. */ - private final transient boolean sensitive; - - //----------------------------------------------------------------------- - /** - * Factory method to create an IOCase from a name. - * - * @param name the name to find - * @return the IOCase object - * @throws IllegalArgumentException if the name is invalid - */ - public static IOCase forName(String name) { - if (IOCase.SENSITIVE.name.equals(name)){ - return IOCase.SENSITIVE; - } - if (IOCase.INSENSITIVE.name.equals(name)){ - return IOCase.INSENSITIVE; - } - if (IOCase.SYSTEM.name.equals(name)){ - return IOCase.SYSTEM; - } - throw new IllegalArgumentException("Invalid IOCase name: " + name); - } - - //----------------------------------------------------------------------- - /** - * Private constructor. - * - * @param name the name - * @param sensitive the sensitivity - */ - private IOCase(String name, boolean sensitive) { - this.name = name; - this.sensitive = sensitive; - } - - /** - * Replaces the enumeration from the stream with a real one. - * This ensures that the correct flag is set for SYSTEM. - * - * @return the resolved object - */ - private Object readResolve() { - return forName(name); - } - - //----------------------------------------------------------------------- - /** - * Gets the name of the constant. - * - * @return the name of the constant - */ - public String getName() { - return name; - } - - /** - * Does the object represent case sensitive comparison. - * - * @return true if case sensitive - */ - public boolean isCaseSensitive() { - return sensitive; - } - - //----------------------------------------------------------------------- - /** - * Compares two strings using the case-sensitivity rule. - *

- * This method mimics {@link String#compareTo} but takes case-sensitivity - * into account. - * - * @param str1 the first string to compare, not null - * @param str2 the second string to compare, not null - * @return true if equal using the case rules - * @throws NullPointerException if either string is null - */ - public int checkCompareTo(String str1, String str2) { - if (str1 == null || str2 == null) { - throw new NullPointerException("The strings must not be null"); - } - return sensitive ? str1.compareTo(str2) : str1.compareToIgnoreCase(str2); - } - - /** - * Compares two strings using the case-sensitivity rule. - *

- * This method mimics {@link String#equals} but takes case-sensitivity - * into account. - * - * @param str1 the first string to compare, not null - * @param str2 the second string to compare, not null - * @return true if equal using the case rules - * @throws NullPointerException if either string is null - */ - public boolean checkEquals(String str1, String str2) { - if (str1 == null || str2 == null) { - throw new NullPointerException("The strings must not be null"); - } - return sensitive ? str1.equals(str2) : str1.equalsIgnoreCase(str2); - } - - /** - * Checks if one string starts with another using the case-sensitivity rule. - *

- * This method mimics {@link String#startsWith(String)} but takes case-sensitivity - * into account. - * - * @param str the string to check, not null - * @param start the start to compare against, not null - * @return true if equal using the case rules - * @throws NullPointerException if either string is null - */ - public boolean checkStartsWith(String str, String start) { - return str.regionMatches(!sensitive, 0, start, 0, start.length()); - } - - /** - * Checks if one string ends with another using the case-sensitivity rule. - *

- * This method mimics {@link String#endsWith} but takes case-sensitivity - * into account. - * - * @param str the string to check, not null - * @param end the end to compare against, not null - * @return true if equal using the case rules - * @throws NullPointerException if either string is null - */ - public boolean checkEndsWith(String str, String end) { - int endLen = end.length(); - return str.regionMatches(!sensitive, str.length() - endLen, end, 0, endLen); - } - - /** - * Checks if one string contains another starting at a specific index using the - * case-sensitivity rule. - *

- * This method mimics parts of {@link String#indexOf(String, int)} - * but takes case-sensitivity into account. - * - * @param str the string to check, not null - * @param strStartIndex the index to start at in str - * @param search the start to search for, not null - * @return the first index of the search String, - * -1 if no match or null string input - * @throws NullPointerException if either string is null - * @since 2.0 - */ - public int checkIndexOf(String str, int strStartIndex, String search) { - int endIndex = str.length() - search.length(); - if (endIndex >= strStartIndex) { - for (int i = strStartIndex; i <= endIndex; i++) { - if (checkRegionMatches(str, i, search)) { - return i; - } - } - } - return -1; - } - - /** - * Checks if one string contains another at a specific index using the case-sensitivity rule. - *

- * This method mimics parts of {@link String#regionMatches(boolean, int, String, int, int)} - * but takes case-sensitivity into account. - * - * @param str the string to check, not null - * @param strStartIndex the index to start at in str - * @param search the start to search for, not null - * @return true if equal using the case rules - * @throws NullPointerException if either string is null - */ - public boolean checkRegionMatches(String str, int strStartIndex, String search) { - return str.regionMatches(!sensitive, strStartIndex, search, 0, search.length()); - } - - //----------------------------------------------------------------------- - /** - * Gets a string describing the sensitivity. - * - * @return a string describing the sensitivity - */ - @Override - public String toString() { - return name; - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/IOExceptionWithCause.java b/apacheandroid/src/main/java/org/apache/commons/io/IOExceptionWithCause.java deleted file mode 100644 index dde1e5280..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/IOExceptionWithCause.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.io; - -import java.io.IOException; - -/** - * Subclasses IOException with the {@link Throwable} constructors missing before Java 6. If you are using Java 6, - * consider this class deprecated and use {@link IOException}. - * - * @version $Id: IOExceptionWithCause.java 1304052 2012-03-22 20:55:29Z ggregory $ - * @since 1.4 - */ -public class IOExceptionWithCause extends IOException { - - /** - * Defines the serial version UID. - */ - private static final long serialVersionUID = 1L; - - /** - * Constructs a new instance with the given message and cause. - *

- * As specified in {@link Throwable}, the message in the given cause is not used in this instance's - * message. - *

- * - * @param message - * the message (see {@link #getMessage()}) - * @param cause - * the cause (see {@link #getCause()}). A null value is allowed. - */ - public IOExceptionWithCause(String message, Throwable cause) { - super(message); - this.initCause(cause); - } - - /** - * Constructs a new instance with the given cause. - *

- * The message is set to cause==null ? null : cause.toString(), which by default contains the class - * and message of cause. This constructor is useful for call sites that just wrap another throwable. - *

- * - * @param cause - * the cause (see {@link #getCause()}). A null value is allowed. - */ - public IOExceptionWithCause(Throwable cause) { - super(cause == null ? null : cause.toString()); - this.initCause(cause); - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/IOUtils.java b/apacheandroid/src/main/java/org/apache/commons/io/IOUtils.java deleted file mode 100644 index 902a6daeb..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/IOUtils.java +++ /dev/null @@ -1,2218 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io; - -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.CharArrayWriter; -import java.io.Closeable; -import java.io.EOFException; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.Reader; -import java.io.Writer; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.URI; -import java.net.URL; -import java.nio.channels.Selector; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.apache.commons.io.output.ByteArrayOutputStream; -import org.apache.commons.io.output.StringBuilderWriter; - -/** - * General IO stream manipulation utilities. - *

- * This class provides static utility methods for input/output operations. - *

    - *
  • closeQuietly - these methods close a stream ignoring nulls and exceptions - *
  • toXxx/read - these methods read data from a stream - *
  • write - these methods write data to a stream - *
  • copy - these methods copy all the data from one stream to another - *
  • contentEquals - these methods compare the content of two streams - *
- *

- * The byte-to-char methods and char-to-byte methods involve a conversion step. - * Two methods are provided in each case, one that uses the platform default - * encoding and the other which allows you to specify an encoding. You are - * encouraged to always specify an encoding because relying on the platform - * default can lead to unexpected results, for example when moving from - * development to production. - *

- * All the methods in this class that read a stream are buffered internally. - * This means that there is no cause to use a BufferedInputStream - * or BufferedReader. The default buffer size of 4K has been shown - * to be efficient in tests. - *

- * Wherever possible, the methods in this class do not flush or close - * the stream. This is to avoid making non-portable assumptions about the - * streams' origin and further use. Thus the caller is still responsible for - * closing streams after use. - *

- * Origin of code: Excalibur. - * - * @version $Id: IOUtils.java 1304177 2012-03-23 03:36:44Z ggregory $ - */ -public class IOUtils { - // NOTE: This class is focussed on InputStream, OutputStream, Reader and - // Writer. Each method should take at least one of these as a parameter, - // or return one of them. - - private static final int EOF = -1; - /** - * The Unix directory separator character. - */ - public static final char DIR_SEPARATOR_UNIX = '/'; - /** - * The Windows directory separator character. - */ - public static final char DIR_SEPARATOR_WINDOWS = '\\'; - /** - * The system directory separator character. - */ - public static final char DIR_SEPARATOR = File.separatorChar; - /** - * The Unix line separator string. - */ - public static final String LINE_SEPARATOR_UNIX = "\n"; - /** - * The Windows line separator string. - */ - public static final String LINE_SEPARATOR_WINDOWS = "\r\n"; - /** - * The system line separator string. - */ - public static final String LINE_SEPARATOR; - - static { - // avoid security issues - StringBuilderWriter buf = new StringBuilderWriter(4); - PrintWriter out = new PrintWriter(buf); - out.println(); - LINE_SEPARATOR = buf.toString(); - out.close(); - } - - /** - * The default buffer size ({@value}) to use for - * {@link #copyLarge(InputStream, OutputStream)} - * and - * {@link #copyLarge(Reader, Writer)} - */ - private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; - - /** - * The default buffer size to use for the skip() methods. - */ - private static final int SKIP_BUFFER_SIZE = 2048; - - // Allocated in the relevant skip method if necessary. - /* - * N.B. no need to synchronize these because: - * - we don't care if the buffer is created multiple times (the data is ignored) - * - we always use the same size buffer, so if it it is recreated it will still be OK - * (if the buffer size were variable, we would need to synch. to ensure some other thread - * did not create a smaller one) - */ - private static char[] SKIP_CHAR_BUFFER; - private static byte[] SKIP_BYTE_BUFFER; - - /** - * Instances should NOT be constructed in standard programming. - */ - public IOUtils() { - super(); - } - - //----------------------------------------------------------------------- - /** - * Unconditionally close an Reader. - *

- * Equivalent to {@link Reader#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - *

- * Example code: - *

-     *   char[] data = new char[1024];
-     *   Reader in = null;
-     *   try {
-     *       in = new FileReader("foo.txt");
-     *       in.read(data);
-     *       in.close(); //close errors are handled
-     *   } catch (Exception e) {
-     *       // error handling
-     *   } finally {
-     *       IOUtils.closeQuietly(in);
-     *   }
-     * 
- * - * @param input the Reader to close, may be null or already closed - */ - public static void closeQuietly(Reader input) { - closeQuietly((Closeable)input); - } - - /** - * Unconditionally close a Writer. - *

- * Equivalent to {@link Writer#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - *

- * Example code: - *

-     *   Writer out = null;
-     *   try {
-     *       out = new StringWriter();
-     *       out.write("Hello World");
-     *       out.close(); //close errors are handled
-     *   } catch (Exception e) {
-     *       // error handling
-     *   } finally {
-     *       IOUtils.closeQuietly(out);
-     *   }
-     * 
- * - * @param output the Writer to close, may be null or already closed - */ - public static void closeQuietly(Writer output) { - closeQuietly((Closeable)output); - } - - /** - * Unconditionally close an InputStream. - *

- * Equivalent to {@link InputStream#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - *

- * Example code: - *

-     *   byte[] data = new byte[1024];
-     *   InputStream in = null;
-     *   try {
-     *       in = new FileInputStream("foo.txt");
-     *       in.read(data);
-     *       in.close(); //close errors are handled
-     *   } catch (Exception e) {
-     *       // error handling
-     *   } finally {
-     *       IOUtils.closeQuietly(in);
-     *   }
-     * 
- * - * @param input the InputStream to close, may be null or already closed - */ - public static void closeQuietly(InputStream input) { - closeQuietly((Closeable)input); - } - - /** - * Unconditionally close an OutputStream. - *

- * Equivalent to {@link OutputStream#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - *

- * Example code: - *

-     * byte[] data = "Hello, World".getBytes();
-     *
-     * OutputStream out = null;
-     * try {
-     *     out = new FileOutputStream("foo.txt");
-     *     out.write(data);
-     *     out.close(); //close errors are handled
-     * } catch (IOException e) {
-     *     // error handling
-     * } finally {
-     *     IOUtils.closeQuietly(out);
-     * }
-     * 
- * - * @param output the OutputStream to close, may be null or already closed - */ - public static void closeQuietly(OutputStream output) { - closeQuietly((Closeable)output); - } - - /** - * Unconditionally close a Closeable. - *

- * Equivalent to {@link Closeable#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - *

- * Example code: - *

-     *   Closeable closeable = null;
-     *   try {
-     *       closeable = new FileReader("foo.txt");
-     *       // process closeable
-     *       closeable.close();
-     *   } catch (Exception e) {
-     *       // error handling
-     *   } finally {
-     *       IOUtils.closeQuietly(closeable);
-     *   }
-     * 
- * - * @param closeable the object to close, may be null or already closed - * @since 2.0 - */ - public static void closeQuietly(Closeable closeable) { - try { - if (closeable != null) { - closeable.close(); - } - } catch (IOException ioe) { - // ignore - } - } - - /** - * Unconditionally close a Socket. - *

- * Equivalent to {@link Socket#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - *

- * Example code: - *

-     *   Socket socket = null;
-     *   try {
-     *       socket = new Socket("http://www.foo.com/", 80);
-     *       // process socket
-     *       socket.close();
-     *   } catch (Exception e) {
-     *       // error handling
-     *   } finally {
-     *       IOUtils.closeQuietly(socket);
-     *   }
-     * 
- * - * @param sock the Socket to close, may be null or already closed - * @since 2.0 - */ - public static void closeQuietly(Socket sock){ - if (sock != null){ - try { - sock.close(); - } catch (IOException ioe) { - // ignored - } - } - } - - /** - * Unconditionally close a Selector. - *

- * Equivalent to {@link Selector#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - *

- * Example code: - *

-     *   Selector selector = null;
-     *   try {
-     *       selector = Selector.open();
-     *       // process socket
-     *       
-     *   } catch (Exception e) {
-     *       // error handling
-     *   } finally {
-     *       IOUtils.closeQuietly(selector);
-     *   }
-     * 
- * - * @param selector the Selector to close, may be null or already closed - * @since 2.2 - */ - public static void closeQuietly(Selector selector){ - if (selector != null){ - try { - selector.close(); - } catch (IOException ioe) { - // ignored - } - } - } - - /** - * Unconditionally close a ServerSocket. - *

- * Equivalent to {@link ServerSocket#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - *

- * Example code: - *

-     *   ServerSocket socket = null;
-     *   try {
-     *       socket = new ServerSocket();
-     *       // process socket
-     *       socket.close();
-     *   } catch (Exception e) {
-     *       // error handling
-     *   } finally {
-     *       IOUtils.closeQuietly(socket);
-     *   }
-     * 
- * - * @param sock the ServerSocket to close, may be null or already closed - * @since 2.2 - */ - public static void closeQuietly(ServerSocket sock){ - if (sock != null){ - try { - sock.close(); - } catch (IOException ioe) { - // ignored - } - } - } - - /** - * Fetches entire contents of an InputStream and represent - * same data as result InputStream. - *

- * This method is useful where, - *

    - *
  • Source InputStream is slow.
  • - *
  • It has network resources associated, so we cannot keep it open for - * long time.
  • - *
  • It has network timeout associated.
  • - *
- * It can be used in favor of {@link #toByteArray(InputStream)}, since it - * avoids unnecessary allocation and copy of byte[].
- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input Stream to be fully buffered. - * @return A fully buffered stream. - * @throws IOException if an I/O error occurs - * @since 2.0 - */ - public static InputStream toBufferedInputStream(InputStream input) throws IOException { - return ByteArrayOutputStream.toBufferedInputStream(input); - } - - /** - * Returns the given reader if it is a {@link BufferedReader}, otherwise creates a toBufferedReader for the given - * reader. - * - * @param reader - * the reader to wrap or return - * @return the given reader or a new {@link BufferedReader} for the given reader - * @since 2.2 - */ - public static BufferedReader toBufferedReader(Reader reader) { - return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); - } - - // read toByteArray - //----------------------------------------------------------------------- - /** - * Get the contents of an InputStream as a byte[]. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input the InputStream to read from - * @return the requested byte array - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - */ - public static byte[] toByteArray(InputStream input) throws IOException { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - copy(input, output); - return output.toByteArray(); - } - - /** - * Get contents of an InputStream as a byte[]. - * Use this method instead of toByteArray(InputStream) - * when InputStream size is known. - * NOTE: the method checks that the length can safely be cast to an int without truncation - * before using {@link IOUtils#toByteArray(java.io.InputStream, int)} to read into the byte array. - * (Arrays can have no more than Integer.MAX_VALUE entries anyway) - * - * @param input the InputStream to read from - * @param size the size of InputStream - * @return the requested byte array - * @throws IOException if an I/O error occurs or InputStream size differ from parameter size - * @throws IllegalArgumentException if size is less than zero or size is greater than Integer.MAX_VALUE - * @see IOUtils#toByteArray(java.io.InputStream, int) - * @since 2.1 - */ - public static byte[] toByteArray(InputStream input, long size) throws IOException { - - if(size > Integer.MAX_VALUE) { - throw new IllegalArgumentException("Size cannot be greater than Integer max value: " + size); - } - - return toByteArray(input, (int) size); - } - - /** - * Get the contents of an InputStream as a byte[]. - * Use this method instead of toByteArray(InputStream) - * when InputStream size is known - * @param input the InputStream to read from - * @param size the size of InputStream - * @return the requested byte array - * @throws IOException if an I/O error occurs or InputStream size differ from parameter size - * @throws IllegalArgumentException if size is less than zero - * @since 2.1 - */ - public static byte[] toByteArray(InputStream input, int size) throws IOException { - - if (size < 0) { - throw new IllegalArgumentException("Size must be equal or greater than zero: " + size); - } - - if (size == 0) { - return new byte[0]; - } - - byte[] data = new byte[size]; - int offset = 0; - int readed; - - while (offset < size && (readed = input.read(data, offset, size - offset)) != EOF) { - offset += readed; - } - - if (offset != size) { - throw new IOException("Unexpected readed size. current: " + offset + ", excepted: " + size); - } - - return data; - } - - /** - * Get the contents of a Reader as a byte[] - * using the default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input the Reader to read from - * @return the requested byte array - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - */ - public static byte[] toByteArray(Reader input) throws IOException { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - copy(input, output); - return output.toByteArray(); - } - - /** - * Get the contents of a Reader as a byte[] - * using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input the Reader to read from - * @param encoding the encoding to use, null means platform default - * @return the requested byte array - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static byte[] toByteArray(Reader input, String encoding) - throws IOException { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - copy(input, output, encoding); - return output.toByteArray(); - } - - /** - * Get the contents of a String as a byte[] - * using the default character encoding of the platform. - *

- * This is the same as {@link String#getBytes()}. - * - * @param input the String to convert - * @return the requested byte array - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs (never occurs) - * @deprecated Use {@link String#getBytes()} - */ - @Deprecated - public static byte[] toByteArray(String input) throws IOException { - return input.getBytes(); - } - - // read char[] - //----------------------------------------------------------------------- - /** - * Get the contents of an InputStream as a character array - * using the default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param is the InputStream to read from - * @return the requested character array - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static char[] toCharArray(InputStream is) throws IOException { - CharArrayWriter output = new CharArrayWriter(); - copy(is, output); - return output.toCharArray(); - } - - /** - * Get the contents of an InputStream as a character array - * using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param is the InputStream to read from - * @param encoding the encoding to use, null means platform default - * @return the requested character array - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static char[] toCharArray(InputStream is, String encoding) - throws IOException { - CharArrayWriter output = new CharArrayWriter(); - copy(is, output, encoding); - return output.toCharArray(); - } - - /** - * Get the contents of a Reader as a character array. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input the Reader to read from - * @return the requested character array - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static char[] toCharArray(Reader input) throws IOException { - CharArrayWriter sw = new CharArrayWriter(); - copy(input, sw); - return sw.toCharArray(); - } - - // read toString - //----------------------------------------------------------------------- - /** - * Get the contents of an InputStream as a String - * using the default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input the InputStream to read from - * @return the requested String - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - */ - public static String toString(InputStream input) throws IOException { - return toString(input, null); - } - - /** - * Get the contents of an InputStream as a String - * using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input the InputStream to read from - * @param encoding the encoding to use, null means platform default - * @return the requested String - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - */ - public static String toString(InputStream input, String encoding) - throws IOException { - StringBuilderWriter sw = new StringBuilderWriter(); - copy(input, sw, encoding); - return sw.toString(); - } - - /** - * Get the contents of a Reader as a String. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input the Reader to read from - * @return the requested String - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - */ - public static String toString(Reader input) throws IOException { - StringBuilderWriter sw = new StringBuilderWriter(); - copy(input, sw); - return sw.toString(); - } - - /** - * Gets the contents at the given URI. - * - * @param uri - * The URI source. - * @return The contents of the URL as a String. - * @throws IOException if an I/O exception occurs. - * @since 2.1. - */ - public static String toString(URI uri) throws IOException { - return toString(uri, null); - } - - /** - * Gets the contents at the given URI. - * - * @param uri - * The URI source. - * @param encoding - * The encoding name for the URL contents. - * @return The contents of the URL as a String. - * @throws IOException if an I/O exception occurs. - * @since 2.1. - */ - public static String toString(URI uri, String encoding) throws IOException { - return toString(uri.toURL(), encoding); - } - - /** - * Gets the contents at the given URL. - * - * @param url - * The URL source. - * @return The contents of the URL as a String. - * @throws IOException if an I/O exception occurs. - * @since 2.1. - */ - public static String toString(URL url) throws IOException { - return toString(url, null); - } - - /** - * Gets the contents at the given URL. - * - * @param url - * The URL source. - * @param encoding - * The encoding name for the URL contents. - * @return The contents of the URL as a String. - * @throws IOException if an I/O exception occurs. - * @since 2.1. - */ - public static String toString(URL url, String encoding) throws IOException { - InputStream inputStream = url.openStream(); - try { - return toString(inputStream, encoding); - } finally { - inputStream.close(); - } - } - - /** - * Get the contents of a byte[] as a String - * using the default character encoding of the platform. - * - * @param input the byte array to read from - * @return the requested String - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs (never occurs) - * @deprecated Use {@link String#String(byte[])} - */ - @Deprecated - public static String toString(byte[] input) throws IOException { - return new String(input); - } - - /** - * Get the contents of a byte[] as a String - * using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - * - * @param input the byte array to read from - * @param encoding the encoding to use, null means platform default - * @return the requested String - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs (never occurs) - * @deprecated Use {@link String#String(byte[],String)} - */ - @Deprecated - public static String toString(byte[] input, String encoding) - throws IOException { - if (encoding == null) { - return new String(input); - } else { - return new String(input, encoding); - } - } - - // readLines - //----------------------------------------------------------------------- - /** - * Get the contents of an InputStream as a list of Strings, - * one entry per line, using the default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input the InputStream to read from, not null - * @return the list of Strings, never null - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static List readLines(InputStream input) throws IOException { - InputStreamReader reader = new InputStreamReader(input); - return readLines(reader); - } - - /** - * Get the contents of an InputStream as a list of Strings, - * one entry per line, using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input the InputStream to read from, not null - * @param encoding the encoding to use, null means platform default - * @return the list of Strings, never null - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static List readLines(InputStream input, String encoding) throws IOException { - if (encoding == null) { - return readLines(input); - } else { - InputStreamReader reader = new InputStreamReader(input, encoding); - return readLines(reader); - } - } - - /** - * Get the contents of a Reader as a list of Strings, - * one entry per line. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input the Reader to read from, not null - * @return the list of Strings, never null - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static List readLines(Reader input) throws IOException { - BufferedReader reader = toBufferedReader(input); - List list = new ArrayList(); - String line = reader.readLine(); - while (line != null) { - list.add(line); - line = reader.readLine(); - } - return list; - } - - // lineIterator - //----------------------------------------------------------------------- - /** - * Return an Iterator for the lines in a Reader. - *

- * LineIterator holds a reference to the open - * Reader specified here. When you have finished with the - * iterator you should close the reader to free internal resources. - * This can be done by closing the reader directly, or by calling - * {@link LineIterator#close()} or {@link LineIterator#closeQuietly(LineIterator)}. - *

- * The recommended usage pattern is: - *

-     * try {
-     *   LineIterator it = IOUtils.lineIterator(reader);
-     *   while (it.hasNext()) {
-     *     String line = it.nextLine();
-     *     /// do something with line
-     *   }
-     * } finally {
-     *   IOUtils.closeQuietly(reader);
-     * }
-     * 
- * - * @param reader the Reader to read from, not null - * @return an Iterator of the lines in the reader, never null - * @throws IllegalArgumentException if the reader is null - * @since 1.2 - */ - public static LineIterator lineIterator(Reader reader) { - return new LineIterator(reader); - } - - /** - * Return an Iterator for the lines in an InputStream, using - * the character encoding specified (or default encoding if null). - *

- * LineIterator holds a reference to the open - * InputStream specified here. When you have finished with - * the iterator you should close the stream to free internal resources. - * This can be done by closing the stream directly, or by calling - * {@link LineIterator#close()} or {@link LineIterator#closeQuietly(LineIterator)}. - *

- * The recommended usage pattern is: - *

-     * try {
-     *   LineIterator it = IOUtils.lineIterator(stream, "UTF-8");
-     *   while (it.hasNext()) {
-     *     String line = it.nextLine();
-     *     /// do something with line
-     *   }
-     * } finally {
-     *   IOUtils.closeQuietly(stream);
-     * }
-     * 
- * - * @param input the InputStream to read from, not null - * @param encoding the encoding to use, null means platform default - * @return an Iterator of the lines in the reader, never null - * @throws IllegalArgumentException if the input is null - * @throws IOException if an I/O error occurs, such as if the encoding is invalid - * @since 1.2 - */ - public static LineIterator lineIterator(InputStream input, String encoding) - throws IOException { - Reader reader = null; - if (encoding == null) { - reader = new InputStreamReader(input); - } else { - reader = new InputStreamReader(input, encoding); - } - return new LineIterator(reader); - } - - //----------------------------------------------------------------------- - /** - * Convert the specified CharSequence to an input stream, encoded as bytes - * using the default character encoding of the platform. - * - * @param input the CharSequence to convert - * @return an input stream - * @since 2.0 - */ - public static InputStream toInputStream(CharSequence input) { - return toInputStream(input.toString()); - } - - /** - * Convert the specified CharSequence to an input stream, encoded as bytes - * using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - * - * @param input the CharSequence to convert - * @param encoding the encoding to use, null means platform default - * @throws IOException if the encoding is invalid - * @return an input stream - * @since 2.0 - */ - public static InputStream toInputStream(CharSequence input, String encoding) throws IOException { - return toInputStream(input.toString(), encoding); - } - - //----------------------------------------------------------------------- - /** - * Convert the specified string to an input stream, encoded as bytes - * using the default character encoding of the platform. - * - * @param input the string to convert - * @return an input stream - * @since 1.1 - */ - public static InputStream toInputStream(String input) { - byte[] bytes = input.getBytes(); - return new ByteArrayInputStream(bytes); - } - - /** - * Convert the specified string to an input stream, encoded as bytes - * using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - * - * @param input the string to convert - * @param encoding the encoding to use, null means platform default - * @throws IOException if the encoding is invalid - * @return an input stream - * @since 1.1 - */ - public static InputStream toInputStream(String input, String encoding) throws IOException { - byte[] bytes = encoding != null ? input.getBytes(encoding) : input.getBytes(); - return new ByteArrayInputStream(bytes); - } - - // write byte[] - //----------------------------------------------------------------------- - /** - * Writes bytes from a byte[] to an OutputStream. - * - * @param data the byte array to write, do not modify during output, - * null ignored - * @param output the OutputStream to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void write(byte[] data, OutputStream output) - throws IOException { - if (data != null) { - output.write(data); - } - } - - /** - * Writes bytes from a byte[] to chars on a Writer - * using the default character encoding of the platform. - *

- * This method uses {@link String#String(byte[])}. - * - * @param data the byte array to write, do not modify during output, - * null ignored - * @param output the Writer to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void write(byte[] data, Writer output) throws IOException { - if (data != null) { - output.write(new String(data)); - } - } - - /** - * Writes bytes from a byte[] to chars on a Writer - * using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#String(byte[], String)}. - * - * @param data the byte array to write, do not modify during output, - * null ignored - * @param output the Writer to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void write(byte[] data, Writer output, String encoding) - throws IOException { - if (data != null) { - if (encoding == null) { - write(data, output); - } else { - output.write(new String(data, encoding)); - } - } - } - - // write char[] - //----------------------------------------------------------------------- - /** - * Writes chars from a char[] to a Writer - * using the default character encoding of the platform. - * - * @param data the char array to write, do not modify during output, - * null ignored - * @param output the Writer to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void write(char[] data, Writer output) throws IOException { - if (data != null) { - output.write(data); - } - } - - /** - * Writes chars from a char[] to bytes on an - * OutputStream. - *

- * This method uses {@link String#String(char[])} and - * {@link String#getBytes()}. - * - * @param data the char array to write, do not modify during output, - * null ignored - * @param output the OutputStream to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void write(char[] data, OutputStream output) - throws IOException { - if (data != null) { - output.write(new String(data).getBytes()); - } - } - - /** - * Writes chars from a char[] to bytes on an - * OutputStream using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#String(char[])} and - * {@link String#getBytes(String)}. - * - * @param data the char array to write, do not modify during output, - * null ignored - * @param output the OutputStream to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void write(char[] data, OutputStream output, String encoding) - throws IOException { - if (data != null) { - if (encoding == null) { - write(data, output); - } else { - output.write(new String(data).getBytes(encoding)); - } - } - } - - // write CharSequence - //----------------------------------------------------------------------- - /** - * Writes chars from a CharSequence to a Writer. - * - * @param data the CharSequence to write, null ignored - * @param output the Writer to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 2.0 - */ - public static void write(CharSequence data, Writer output) throws IOException { - if (data != null) { - write(data.toString(), output); - } - } - - /** - * Writes chars from a CharSequence to bytes on an - * OutputStream using the default character encoding of the - * platform. - *

- * This method uses {@link String#getBytes()}. - * - * @param data the CharSequence to write, null ignored - * @param output the OutputStream to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 2.0 - */ - public static void write(CharSequence data, OutputStream output) - throws IOException { - if (data != null) { - write(data.toString(), output); - } - } - - /** - * Writes chars from a CharSequence to bytes on an - * OutputStream using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#getBytes(String)}. - * - * @param data the CharSequence to write, null ignored - * @param output the OutputStream to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 2.0 - */ - public static void write(CharSequence data, OutputStream output, String encoding) - throws IOException { - if (data != null) { - write(data.toString(), output, encoding); - } - } - - // write String - //----------------------------------------------------------------------- - /** - * Writes chars from a String to a Writer. - * - * @param data the String to write, null ignored - * @param output the Writer to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void write(String data, Writer output) throws IOException { - if (data != null) { - output.write(data); - } - } - - /** - * Writes chars from a String to bytes on an - * OutputStream using the default character encoding of the - * platform. - *

- * This method uses {@link String#getBytes()}. - * - * @param data the String to write, null ignored - * @param output the OutputStream to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void write(String data, OutputStream output) - throws IOException { - if (data != null) { - output.write(data.getBytes()); - } - } - - /** - * Writes chars from a String to bytes on an - * OutputStream using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#getBytes(String)}. - * - * @param data the String to write, null ignored - * @param output the OutputStream to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void write(String data, OutputStream output, String encoding) - throws IOException { - if (data != null) { - if (encoding == null) { - write(data, output); - } else { - output.write(data.getBytes(encoding)); - } - } - } - - // write StringBuffer - //----------------------------------------------------------------------- - /** - * Writes chars from a StringBuffer to a Writer. - * - * @param data the StringBuffer to write, null ignored - * @param output the Writer to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - * @deprecated replaced by write(CharSequence, Writer) - */ - @Deprecated - public static void write(StringBuffer data, Writer output) - throws IOException { - if (data != null) { - output.write(data.toString()); - } - } - - /** - * Writes chars from a StringBuffer to bytes on an - * OutputStream using the default character encoding of the - * platform. - *

- * This method uses {@link String#getBytes()}. - * - * @param data the StringBuffer to write, null ignored - * @param output the OutputStream to write to - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - * @deprecated replaced by write(CharSequence, OutputStream) - */ - @Deprecated - public static void write(StringBuffer data, OutputStream output) - throws IOException { - if (data != null) { - output.write(data.toString().getBytes()); - } - } - - /** - * Writes chars from a StringBuffer to bytes on an - * OutputStream using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#getBytes(String)}. - * - * @param data the StringBuffer to write, null ignored - * @param output the OutputStream to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - * @deprecated replaced by write(CharSequence, OutputStream, String) - */ - @Deprecated - public static void write(StringBuffer data, OutputStream output, - String encoding) throws IOException { - if (data != null) { - if (encoding == null) { - write(data, output); - } else { - output.write(data.toString().getBytes(encoding)); - } - } - } - - // writeLines - //----------------------------------------------------------------------- - /** - * Writes the toString() value of each item in a collection to - * an OutputStream line by line, using the default character - * encoding of the platform and the specified line ending. - * - * @param lines the lines to write, null entries produce blank lines - * @param lineEnding the line separator to use, null is system default - * @param output the OutputStream to write to, not null, not closed - * @throws NullPointerException if the output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void writeLines(Collection lines, String lineEnding, - OutputStream output) throws IOException { - if (lines == null) { - return; - } - if (lineEnding == null) { - lineEnding = LINE_SEPARATOR; - } - for (Object line : lines) { - if (line != null) { - output.write(line.toString().getBytes()); - } - output.write(lineEnding.getBytes()); - } - } - - /** - * Writes the toString() value of each item in a collection to - * an OutputStream line by line, using the specified character - * encoding and the specified line ending. - *

- * Character encoding names can be found at - * IANA. - * - * @param lines the lines to write, null entries produce blank lines - * @param lineEnding the line separator to use, null is system default - * @param output the OutputStream to write to, not null, not closed - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if the output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void writeLines(Collection lines, String lineEnding, - OutputStream output, String encoding) throws IOException { - if (encoding == null) { - writeLines(lines, lineEnding, output); - } else { - if (lines == null) { - return; - } - if (lineEnding == null) { - lineEnding = LINE_SEPARATOR; - } - for (Object line : lines) { - if (line != null) { - output.write(line.toString().getBytes(encoding)); - } - output.write(lineEnding.getBytes(encoding)); - } - } - } - - /** - * Writes the toString() value of each item in a collection to - * a Writer line by line, using the specified line ending. - * - * @param lines the lines to write, null entries produce blank lines - * @param lineEnding the line separator to use, null is system default - * @param writer the Writer to write to, not null, not closed - * @throws NullPointerException if the input is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void writeLines(Collection lines, String lineEnding, - Writer writer) throws IOException { - if (lines == null) { - return; - } - if (lineEnding == null) { - lineEnding = LINE_SEPARATOR; - } - for (Object line : lines) { - if (line != null) { - writer.write(line.toString()); - } - writer.write(lineEnding); - } - } - - // copy from InputStream - //----------------------------------------------------------------------- - /** - * Copy bytes from an InputStream to an - * OutputStream. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * Large streams (over 2GB) will return a bytes copied value of - * -1 after the copy has completed since the correct - * number of bytes cannot be returned as an int. For large streams - * use the copyLarge(InputStream, OutputStream) method. - * - * @param input the InputStream to read from - * @param output the OutputStream to write to - * @return the number of bytes copied, or -1 if > Integer.MAX_VALUE - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static int copy(InputStream input, OutputStream output) throws IOException { - long count = copyLarge(input, output); - if (count > Integer.MAX_VALUE) { - return -1; - } - return (int) count; - } - - /** - * Copy bytes from a large (over 2GB) InputStream to an - * OutputStream. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}. - * - * @param input the InputStream to read from - * @param output the OutputStream to write to - * @return the number of bytes copied - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 1.3 - */ - public static long copyLarge(InputStream input, OutputStream output) - throws IOException { - return copyLarge(input, output, new byte[DEFAULT_BUFFER_SIZE]); - } - - /** - * Copy bytes from a large (over 2GB) InputStream to an - * OutputStream. - *

- * This method uses the provided buffer, so there is no need to use a - * BufferedInputStream. - *

- * - * @param input the InputStream to read from - * @param output the OutputStream to write to - * @param buffer the buffer to use for the copy - * @return the number of bytes copied - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 2.2 - */ - public static long copyLarge(InputStream input, OutputStream output, byte[] buffer) - throws IOException { - long count = 0; - int n = 0; - while (EOF != (n = input.read(buffer))) { - output.write(buffer, 0, n); - count += n; - } - return count; - } - - /** - * Copy some or all bytes from a large (over 2GB) InputStream to an - * OutputStream, optionally skipping input bytes. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}. - * - * @param input the InputStream to read from - * @param output the OutputStream to write to - * @param inputOffset : number of bytes to skip from input before copying - * -ve values are ignored - * @param length : number of bytes to copy. -ve means all - * @return the number of bytes copied - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 2.2 - */ - public static long copyLarge(InputStream input, OutputStream output, long inputOffset, long length) - throws IOException { - return copyLarge(input, output, inputOffset, length, new byte[DEFAULT_BUFFER_SIZE]); - } - - /** - * Copy some or all bytes from a large (over 2GB) InputStream to an - * OutputStream, optionally skipping input bytes. - *

- * This method uses the provided buffer, so there is no need to use a - * BufferedInputStream. - *

- * - * @param input the InputStream to read from - * @param output the OutputStream to write to - * @param inputOffset : number of bytes to skip from input before copying - * -ve values are ignored - * @param length : number of bytes to copy. -ve means all - * @param buffer the buffer to use for the copy - * - * @return the number of bytes copied - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 2.2 - */ - public static long copyLarge(InputStream input, OutputStream output, - final long inputOffset, final long length, byte[] buffer) throws IOException { - if (inputOffset > 0) { - skipFully(input, inputOffset); - } - if (length == 0) { - return 0; - } - final int bufferLength = buffer.length; - int bytesToRead = bufferLength; - if (length > 0 && length < bufferLength) { - bytesToRead = (int) length; - } - int read; - long totalRead = 0; - while (bytesToRead > 0 && EOF != (read = input.read(buffer, 0, bytesToRead))) { - output.write(buffer, 0, read); - totalRead += read; - if (length > 0) { // only adjust length if not reading to the end - // Note the cast must work because buffer.length is an integer - bytesToRead = (int) Math.min(length - totalRead, bufferLength); - } - } - return totalRead; - } - - /** - * Copy bytes from an InputStream to chars on a - * Writer using the default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * This method uses {@link InputStreamReader}. - * - * @param input the InputStream to read from - * @param output the Writer to write to - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void copy(InputStream input, Writer output) - throws IOException { - InputStreamReader in = new InputStreamReader(input); - copy(in, output); - } - - /** - * Copy bytes from an InputStream to chars on a - * Writer using the specified character encoding. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link InputStreamReader}. - * - * @param input the InputStream to read from - * @param output the Writer to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void copy(InputStream input, Writer output, String encoding) - throws IOException { - if (encoding == null) { - copy(input, output); - } else { - InputStreamReader in = new InputStreamReader(input, encoding); - copy(in, output); - } - } - - // copy from Reader - //----------------------------------------------------------------------- - /** - * Copy chars from a Reader to a Writer. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - *

- * Large streams (over 2GB) will return a chars copied value of - * -1 after the copy has completed since the correct - * number of chars cannot be returned as an int. For large streams - * use the copyLarge(Reader, Writer) method. - * - * @param input the Reader to read from - * @param output the Writer to write to - * @return the number of characters copied, or -1 if > Integer.MAX_VALUE - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static int copy(Reader input, Writer output) throws IOException { - long count = copyLarge(input, output); - if (count > Integer.MAX_VALUE) { - return -1; - } - return (int) count; - } - - /** - * Copy chars from a large (over 2GB) Reader to a Writer. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - *

- * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}. - * - * @param input the Reader to read from - * @param output the Writer to write to - * @return the number of characters copied - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 1.3 - */ - public static long copyLarge(Reader input, Writer output) throws IOException { - return copyLarge(input, output, new char[DEFAULT_BUFFER_SIZE]); - } - - /** - * Copy chars from a large (over 2GB) Reader to a Writer. - *

- * This method uses the provided buffer, so there is no need to use a - * BufferedReader. - *

- * - * @param input the Reader to read from - * @param output the Writer to write to - * @param buffer the buffer to be used for the copy - * @return the number of characters copied - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 2.2 - */ - public static long copyLarge(Reader input, Writer output, char [] buffer) throws IOException { - long count = 0; - int n = 0; - while (EOF != (n = input.read(buffer))) { - output.write(buffer, 0, n); - count += n; - } - return count; - } - - /** - * Copy some or all chars from a large (over 2GB) InputStream to an - * OutputStream, optionally skipping input chars. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - *

- * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}. - * - * @param input the Reader to read from - * @param output the Writer to write to - * @param inputOffset : number of chars to skip from input before copying - * -ve values are ignored - * @param length : number of chars to copy. -ve means all - * @return the number of chars copied - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 2.2 - */ - public static long copyLarge(Reader input, Writer output, final long inputOffset, final long length) - throws IOException { - return copyLarge(input, output, inputOffset, length, new char[DEFAULT_BUFFER_SIZE]); - } - - /** - * Copy some or all chars from a large (over 2GB) InputStream to an - * OutputStream, optionally skipping input chars. - *

- * This method uses the provided buffer, so there is no need to use a - * BufferedReader. - *

- * - * @param input the Reader to read from - * @param output the Writer to write to - * @param inputOffset : number of chars to skip from input before copying - * -ve values are ignored - * @param length : number of chars to copy. -ve means all - * @param buffer the buffer to be used for the copy - * @return the number of chars copied - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 2.2 - */ - public static long copyLarge(Reader input, Writer output, final long inputOffset, final long length, char [] buffer) - throws IOException { - if (inputOffset > 0) { - skipFully(input, inputOffset); - } - if (length == 0) { - return 0; - } - int bytesToRead = buffer.length; - if (length > 0 && length < buffer.length) { - bytesToRead = (int) length; - } - int read; - long totalRead = 0; - while (bytesToRead > 0 && EOF != (read = input.read(buffer, 0, bytesToRead))) { - output.write(buffer, 0, read); - totalRead += read; - if (length > 0) { // only adjust length if not reading to the end - // Note the cast must work because buffer.length is an integer - bytesToRead = (int) Math.min(length - totalRead, buffer.length); - } - } - return totalRead; - } - - /** - * Copy chars from a Reader to bytes on an - * OutputStream using the default character encoding of the - * platform, and calling flush. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - *

- * Due to the implementation of OutputStreamWriter, this method performs a - * flush. - *

- * This method uses {@link OutputStreamWriter}. - * - * @param input the Reader to read from - * @param output the OutputStream to write to - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void copy(Reader input, OutputStream output) - throws IOException { - OutputStreamWriter out = new OutputStreamWriter(output); - copy(input, out); - // XXX Unless anyone is planning on rewriting OutputStreamWriter, we - // have to flush here. - out.flush(); - } - - /** - * Copy chars from a Reader to bytes on an - * OutputStream using the specified character encoding, and - * calling flush. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - *

- * Character encoding names can be found at - * IANA. - *

- * Due to the implementation of OutputStreamWriter, this method performs a - * flush. - *

- * This method uses {@link OutputStreamWriter}. - * - * @param input the Reader to read from - * @param output the OutputStream to write to - * @param encoding the encoding to use, null means platform default - * @throws NullPointerException if the input or output is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static void copy(Reader input, OutputStream output, String encoding) - throws IOException { - if (encoding == null) { - copy(input, output); - } else { - OutputStreamWriter out = new OutputStreamWriter(output, encoding); - copy(input, out); - // XXX Unless anyone is planning on rewriting OutputStreamWriter, - // we have to flush here. - out.flush(); - } - } - - // content equals - //----------------------------------------------------------------------- - /** - * Compare the contents of two Streams to determine if they are equal or - * not. - *

- * This method buffers the input internally using - * BufferedInputStream if they are not already buffered. - * - * @param input1 the first stream - * @param input2 the second stream - * @return true if the content of the streams are equal or they both don't - * exist, false otherwise - * @throws NullPointerException if either input is null - * @throws IOException if an I/O error occurs - */ - public static boolean contentEquals(InputStream input1, InputStream input2) - throws IOException { - if (!(input1 instanceof BufferedInputStream)) { - input1 = new BufferedInputStream(input1); - } - if (!(input2 instanceof BufferedInputStream)) { - input2 = new BufferedInputStream(input2); - } - - int ch = input1.read(); - while (EOF != ch) { - int ch2 = input2.read(); - if (ch != ch2) { - return false; - } - ch = input1.read(); - } - - int ch2 = input2.read(); - return ch2 == EOF; - } - - /** - * Compare the contents of two Readers to determine if they are equal or - * not. - *

- * This method buffers the input internally using - * BufferedReader if they are not already buffered. - * - * @param input1 the first reader - * @param input2 the second reader - * @return true if the content of the readers are equal or they both don't - * exist, false otherwise - * @throws NullPointerException if either input is null - * @throws IOException if an I/O error occurs - * @since 1.1 - */ - public static boolean contentEquals(Reader input1, Reader input2) - throws IOException { - - input1 = toBufferedReader(input1); - input2 = toBufferedReader(input2); - - int ch = input1.read(); - while (EOF != ch) { - int ch2 = input2.read(); - if (ch != ch2) { - return false; - } - ch = input1.read(); - } - - int ch2 = input2.read(); - return ch2 == EOF; - } - - /** - * Compare the contents of two Readers to determine if they are equal or - * not, ignoring EOL characters. - *

- * This method buffers the input internally using - * BufferedReader if they are not already buffered. - * - * @param input1 the first reader - * @param input2 the second reader - * @return true if the content of the readers are equal (ignoring EOL differences), false otherwise - * @throws NullPointerException if either input is null - * @throws IOException if an I/O error occurs - * @since 2.2 - */ - public static boolean contentEqualsIgnoreEOL(Reader input1, Reader input2) - throws IOException { - BufferedReader br1 = toBufferedReader(input1); - BufferedReader br2 = toBufferedReader(input2); - - String line1 = br1.readLine(); - String line2 = br2.readLine(); - while (line1 != null && line2 != null && line1.equals(line2)) { - line1 = br1.readLine(); - line2 = br2.readLine(); - } - return line1 == null ? line2 == null ? true : false : line1.equals(line2); - } - - /** - * Skip bytes from an input byte stream. - * This implementation guarantees that it will read as many bytes - * as possible before giving up; this may not always be the case for - * subclasses of {@link Reader}. - * - * @param input byte stream to skip - * @param toSkip number of bytes to skip. - * @return number of bytes actually skipped. - * - * @see InputStream#skip(long) - * - * @throws IOException if there is a problem reading the file - * @throws IllegalArgumentException if toSkip is negative - * @since 2.0 - */ - public static long skip(InputStream input, long toSkip) throws IOException { - if (toSkip < 0) { - throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip); - } - /* - * N.B. no need to synchronize this because: - we don't care if the buffer is created multiple times (the data - * is ignored) - we always use the same size buffer, so if it it is recreated it will still be OK (if the buffer - * size were variable, we would need to synch. to ensure some other thread did not create a smaller one) - */ - if (SKIP_BYTE_BUFFER == null) { - SKIP_BYTE_BUFFER = new byte[SKIP_BUFFER_SIZE]; - } - long remain = toSkip; - while (remain > 0) { - long n = input.read(SKIP_BYTE_BUFFER, 0, (int) Math.min(remain, SKIP_BUFFER_SIZE)); - if (n < 0) { // EOF - break; - } - remain -= n; - } - return toSkip - remain; - } - - /** - * Skip characters from an input character stream. - * This implementation guarantees that it will read as many characters - * as possible before giving up; this may not always be the case for - * subclasses of {@link Reader}. - * - * @param input character stream to skip - * @param toSkip number of characters to skip. - * @return number of characters actually skipped. - * - * @see Reader#skip(long) - * - * @throws IOException if there is a problem reading the file - * @throws IllegalArgumentException if toSkip is negative - * @since 2.0 - */ - public static long skip(Reader input, long toSkip) throws IOException { - if (toSkip < 0) { - throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip); - } - /* - * N.B. no need to synchronize this because: - we don't care if the buffer is created multiple times (the data - * is ignored) - we always use the same size buffer, so if it it is recreated it will still be OK (if the buffer - * size were variable, we would need to synch. to ensure some other thread did not create a smaller one) - */ - if (SKIP_CHAR_BUFFER == null) { - SKIP_CHAR_BUFFER = new char[SKIP_BUFFER_SIZE]; - } - long remain = toSkip; - while (remain > 0) { - long n = input.read(SKIP_CHAR_BUFFER, 0, (int) Math.min(remain, SKIP_BUFFER_SIZE)); - if (n < 0) { // EOF - break; - } - remain -= n; - } - return toSkip - remain; - } - - /** - * Skip the requested number of bytes or fail if there are not enough left. - *

- * This allows for the possibility that {@link InputStream#skip(long)} may - * not skip as many bytes as requested (most likely because of reaching EOF). - * - * @param input stream to skip - * @param toSkip the number of bytes to skip - * @see InputStream#skip(long) - * - * @throws IOException if there is a problem reading the file - * @throws IllegalArgumentException if toSkip is negative - * @throws EOFException if the number of bytes skipped was incorrect - * @since 2.0 - */ - public static void skipFully(InputStream input, long toSkip) throws IOException { - if (toSkip < 0) { - throw new IllegalArgumentException("Bytes to skip must not be negative: " + toSkip); - } - long skipped = skip(input, toSkip); - if (skipped != toSkip) { - throw new EOFException("Bytes to skip: " + toSkip + " actual: " + skipped); - } - } - - /** - * Skip the requested number of characters or fail if there are not enough left. - *

- * This allows for the possibility that {@link Reader#skip(long)} may - * not skip as many characters as requested (most likely because of reaching EOF). - * - * @param input stream to skip - * @param toSkip the number of characters to skip - * @see Reader#skip(long) - * - * @throws IOException if there is a problem reading the file - * @throws IllegalArgumentException if toSkip is negative - * @throws EOFException if the number of characters skipped was incorrect - * @since 2.0 - */ - public static void skipFully(Reader input, long toSkip) throws IOException { - long skipped = skip(input, toSkip); - if (skipped != toSkip) { - throw new EOFException("Chars to skip: " + toSkip + " actual: " + skipped); - } - } - - - /** - * Read characters from an input character stream. - * This implementation guarantees that it will read as many characters - * as possible before giving up; this may not always be the case for - * subclasses of {@link Reader}. - * - * @param input where to read input from - * @param buffer destination - * @param offset inital offset into buffer - * @param length length to read, must be >= 0 - * @return actual length read; may be less than requested if EOF was reached - * @throws IOException if a read error occurs - * @since 2.2 - */ - public static int read(Reader input, char[] buffer, int offset, int length) throws IOException { - if (length < 0) { - throw new IllegalArgumentException("Length must not be negative: " + length); - } - int remaining = length; - while (remaining > 0) { - int location = length - remaining; - int count = input.read(buffer, offset + location, remaining); - if (EOF == count) { // EOF - break; - } - remaining -= count; - } - return length - remaining; - } - - /** - * Read characters from an input character stream. - * This implementation guarantees that it will read as many characters - * as possible before giving up; this may not always be the case for - * subclasses of {@link Reader}. - * - * @param input where to read input from - * @param buffer destination - * @return actual length read; may be less than requested if EOF was reached - * @throws IOException if a read error occurs - * @since 2.2 - */ - public static int read(Reader input, char[] buffer) throws IOException { - return read(input, buffer, 0, buffer.length); - } - - /** - * Read bytes from an input stream. - * This implementation guarantees that it will read as many bytes - * as possible before giving up; this may not always be the case for - * subclasses of {@link InputStream}. - * - * @param input where to read input from - * @param buffer destination - * @param offset inital offset into buffer - * @param length length to read, must be >= 0 - * @return actual length read; may be less than requested if EOF was reached - * @throws IOException if a read error occurs - * @since 2.2 - */ - public static int read(InputStream input, byte[] buffer, int offset, int length) throws IOException { - if (length < 0) { - throw new IllegalArgumentException("Length must not be negative: " + length); - } - int remaining = length; - while (remaining > 0) { - int location = length - remaining; - int count = input.read(buffer, offset + location, remaining); - if (EOF == count) { // EOF - break; - } - remaining -= count; - } - return length - remaining; - } - - /** - * Read bytes from an input stream. - * This implementation guarantees that it will read as many bytes - * as possible before giving up; this may not always be the case for - * subclasses of {@link InputStream}. - * - * @param input where to read input from - * @param buffer destination - * @return actual length read; may be less than requested if EOF was reached - * @throws IOException if a read error occurs - * @since 2.2 - */ - public static int read(InputStream input, byte[] buffer) throws IOException { - return read(input, buffer, 0, buffer.length); - } - - /** - * Read the requested number of characters or fail if there are not enough left. - *

- * This allows for the possibility that {@link Reader#read(char[], int, int)} may - * not read as many characters as requested (most likely because of reaching EOF). - * - * @param input where to read input from - * @param buffer destination - * @param offset inital offset into buffer - * @param length length to read, must be >= 0 - * - * @throws IOException if there is a problem reading the file - * @throws IllegalArgumentException if length is negative - * @throws EOFException if the number of characters read was incorrect - * @since 2.2 - */ - public static void readFully(Reader input, char[] buffer, int offset, int length) throws IOException { - int actual = read(input, buffer, offset, length); - if (actual != length) { - throw new EOFException("Length to read: " + length + " actual: " + actual); - } - } - - /** - * Read the requested number of characters or fail if there are not enough left. - *

- * This allows for the possibility that {@link Reader#read(char[], int, int)} may - * not read as many characters as requested (most likely because of reaching EOF). - * - * @param input where to read input from - * @param buffer destination - * - * @throws IOException if there is a problem reading the file - * @throws IllegalArgumentException if length is negative - * @throws EOFException if the number of characters read was incorrect - * @since 2.2 - */ - public static void readFully(Reader input, char[] buffer) throws IOException { - readFully(input, buffer, 0, buffer.length); - } - - /** - * Read the requested number of bytes or fail if there are not enough left. - *

- * This allows for the possibility that {@link InputStream#read(byte[], int, int)} may - * not read as many bytes as requested (most likely because of reaching EOF). - * - * @param input where to read input from - * @param buffer destination - * @param offset inital offset into buffer - * @param length length to read, must be >= 0 - * - * @throws IOException if there is a problem reading the file - * @throws IllegalArgumentException if length is negative - * @throws EOFException if the number of bytes read was incorrect - * @since 2.2 - */ - public static void readFully(InputStream input, byte[] buffer, int offset, int length) throws IOException { - int actual = read(input, buffer, offset, length); - if (actual != length) { - throw new EOFException("Length to read: " + length + " actual: " + actual); - } - } - - /** - * Read the requested number of bytes or fail if there are not enough left. - *

- * This allows for the possibility that {@link InputStream#read(byte[], int, int)} may - * not read as many bytes as requested (most likely because of reaching EOF). - * - * @param input where to read input from - * @param buffer destination - * - * @throws IOException if there is a problem reading the file - * @throws IllegalArgumentException if length is negative - * @throws EOFException if the number of bytes read was incorrect - * @since 2.2 - */ - public static void readFully(InputStream input, byte[] buffer) throws IOException { - readFully(input, buffer, 0, buffer.length); - } -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/LineIterator.java b/apacheandroid/src/main/java/org/apache/commons/io/LineIterator.java deleted file mode 100644 index c8cc8c9e1..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/LineIterator.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Reader; -import java.util.Iterator; -import java.util.NoSuchElementException; - -/** - * An Iterator over the lines in a Reader. - *

- * LineIterator holds a reference to an open Reader. - * When you have finished with the iterator you should close the reader - * to free internal resources. This can be done by closing the reader directly, - * or by calling the {@link #close()} or {@link #closeQuietly(LineIterator)} - * method on the iterator. - *

- * The recommended usage pattern is: - *

- * LineIterator it = FileUtils.lineIterator(file, "UTF-8");
- * try {
- *   while (it.hasNext()) {
- *     String line = it.nextLine();
- *     // do something with line
- *   }
- * } finally {
- *   it.close();
- * }
- * 
- * - * @version $Id: LineIterator.java 1304073 2012-03-22 21:19:18Z sebb $ - * @since 1.2 - */ -public class LineIterator implements Iterator { - - // N.B. This class deliberately does not implement Iterable, see https://issues.apache.org/jira/browse/IO-181 - - /** The reader that is being read. */ - private final BufferedReader bufferedReader; - /** The current line. */ - private String cachedLine; - /** A flag indicating if the iterator has been fully read. */ - private boolean finished = false; - - /** - * Constructs an iterator of the lines for a Reader. - * - * @param reader the Reader to read from, not null - * @throws IllegalArgumentException if the reader is null - */ - public LineIterator(final Reader reader) throws IllegalArgumentException { - if (reader == null) { - throw new IllegalArgumentException("Reader must not be null"); - } - if (reader instanceof BufferedReader) { - bufferedReader = (BufferedReader) reader; - } else { - bufferedReader = new BufferedReader(reader); - } - } - - //----------------------------------------------------------------------- - /** - * Indicates whether the Reader has more lines. - * If there is an IOException then {@link #close()} will - * be called on this instance. - * - * @return true if the Reader has more lines - * @throws IllegalStateException if an IO exception occurs - */ - public boolean hasNext() { - if (cachedLine != null) { - return true; - } else if (finished) { - return false; - } else { - try { - while (true) { - String line = bufferedReader.readLine(); - if (line == null) { - finished = true; - return false; - } else if (isValidLine(line)) { - cachedLine = line; - return true; - } - } - } catch(IOException ioe) { - close(); - throw new IllegalStateException(ioe); - } - } - } - - /** - * Overridable method to validate each line that is returned. - * This implementation always returns true. - * @param line the line that is to be validated - * @return true if valid, false to remove from the iterator - */ - protected boolean isValidLine(String line) { - return true; - } - - /** - * Returns the next line in the wrapped Reader. - * - * @return the next line from the input - * @throws NoSuchElementException if there is no line to return - */ - public String next() { - return nextLine(); - } - - /** - * Returns the next line in the wrapped Reader. - * - * @return the next line from the input - * @throws NoSuchElementException if there is no line to return - */ - public String nextLine() { - if (!hasNext()) { - throw new NoSuchElementException("No more lines"); - } - String currentLine = cachedLine; - cachedLine = null; - return currentLine; - } - - /** - * Closes the underlying Reader quietly. - * This method is useful if you only want to process the first few - * lines of a larger file. If you do not close the iterator - * then the Reader remains open. - * This method can safely be called multiple times. - */ - public void close() { - finished = true; - IOUtils.closeQuietly(bufferedReader); - cachedLine = null; - } - - /** - * Unsupported. - * - * @throws UnsupportedOperationException always - */ - public void remove() { - throw new UnsupportedOperationException("Remove unsupported on LineIterator"); - } - - //----------------------------------------------------------------------- - /** - * Closes the iterator, handling null and ignoring exceptions. - * - * @param iterator the iterator to close - */ - public static void closeQuietly(LineIterator iterator) { - if (iterator != null) { - iterator.close(); - } - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/TaggedIOException.java b/apacheandroid/src/main/java/org/apache/commons/io/TaggedIOException.java deleted file mode 100644 index 7b5a3ea53..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/TaggedIOException.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io; - -import java.io.IOException; -import java.io.Serializable; - -/** - * An {@link IOException} decorator that adds a serializable tag to the - * wrapped exception. Both the tag and the original exception can be used - * to determine further processing when this exception is caught. - * - * @since 2.0 - */ -public class TaggedIOException extends IOExceptionWithCause { - - /** - * Generated serial version UID. - */ - private static final long serialVersionUID = -6994123481142850163L; - - /** - * Checks whether the given throwable is tagged with the given tag. - *

- * This check can only succeed if the throwable is a - * {@link TaggedIOException} and the tag is {@link Serializable}, but - * the argument types are intentionally more generic to make it easier - * to use this method without type casts. - *

- * A typical use for this method is in a catch block to - * determine how a caught exception should be handled: - *

-     * Serializable tag = ...;
-     * try {
-     *     ...;
-     * } catch (Throwable t) {
-     *     if (TaggedIOExcepton.isTaggedWith(t, tag)) {
-     *         // special processing for tagged exception
-     *     } else {
-     *         // handling of other kinds of exceptions
-     *     }
-     * }
-     * 
- * - * @param throwable The Throwable object to check - * @param tag tag object - * @return true if the throwable has the specified tag, - * otherwise false - */ - public static boolean isTaggedWith(Throwable throwable, Object tag) { - return tag != null - && throwable instanceof TaggedIOException - && tag.equals(((TaggedIOException) throwable).tag); - } - - /** - * Throws the original {@link IOException} if the given throwable is - * a {@link TaggedIOException} decorator the given tag. Does nothing - * if the given throwable is of a different type or if it is tagged - * with some other tag. - *

- * This method is typically used in a catch block to - * selectively rethrow tagged exceptions. - *

-     * Serializable tag = ...;
-     * try {
-     *     ...;
-     * } catch (Throwable t) {
-     *     TaggedIOExcepton.throwCauseIfTagged(t, tag);
-     *     // handle other kinds of exceptions
-     * }
-     * 
- * - * @param throwable an exception - * @param tag tag object - * @throws IOException original exception from the tagged decorator, if any - */ - public static void throwCauseIfTaggedWith(Throwable throwable, Object tag) - throws IOException { - if (isTaggedWith(throwable, tag)) { - throw ((TaggedIOException) throwable).getCause(); - } - } - - /** - * The tag of this exception. - */ - private final Serializable tag; - - /** - * Creates a tagged wrapper for the given exception. - * - * @param original the exception to be tagged - * @param tag tag of this exception - */ - public TaggedIOException(IOException original, Serializable tag) { - super(original.getMessage(), original); - this.tag = tag; - } - - /** - * Returns the serializable tag object. - * - * @return tag object - */ - public Serializable getTag() { - return tag; - } - - /** - * Returns the wrapped exception. The only difference to the overridden - * {@link Throwable#getCause()} method is the narrower return type. - * - * @return wrapped exception - */ - @Override - public IOException getCause() { - return (IOException) super.getCause(); - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/filefilter/AbstractFileFilter.java b/apacheandroid/src/main/java/org/apache/commons/io/filefilter/AbstractFileFilter.java deleted file mode 100644 index 22f8e10b9..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/filefilter/AbstractFileFilter.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.filefilter; - -import java.io.File; - -/** - * An abstract class which implements the Java FileFilter and FilenameFilter - * interfaces via the IOFileFilter interface. - *

- * Note that a subclass must override one of the accept methods, - * otherwise your class will infinitely loop. - * - * @since 1.0 - * @version $Id: AbstractFileFilter.java 1304052 2012-03-22 20:55:29Z ggregory $ - */ -public abstract class AbstractFileFilter implements IOFileFilter { - - /** - * Checks to see if the File should be accepted by this filter. - * - * @param file the File to check - * @return true if this file matches the test - */ - public boolean accept(File file) { - return accept(file.getParentFile(), file.getName()); - } - - /** - * Checks to see if the File should be accepted by this filter. - * - * @param dir the directory File to check - * @param name the filename within the directory to check - * @return true if this file matches the test - */ - public boolean accept(File dir, String name) { - return accept(new File(dir, name)); - } - - /** - * Provide a String representaion of this file filter. - * - * @return a String representaion - */ - @Override - public String toString() { - return getClass().getSimpleName(); - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/filefilter/DirectoryFileFilter.java b/apacheandroid/src/main/java/org/apache/commons/io/filefilter/DirectoryFileFilter.java deleted file mode 100644 index dbb12b668..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/filefilter/DirectoryFileFilter.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.filefilter; - -import java.io.File; -import java.io.Serializable; - -/** - * This filter accepts Files that are directories. - *

- * For example, here is how to print out a list of the - * current directory's subdirectories: - * - *

- * File dir = new File(".");
- * String[] files = dir.list( DirectoryFileFilter.INSTANCE );
- * for ( int i = 0; i < files.length; i++ ) {
- *     System.out.println(files[i]);
- * }
- * 
- * - * @since 1.0 - * @version $Id: DirectoryFileFilter.java 1304052 2012-03-22 20:55:29Z ggregory $ - * - * @see FileFilterUtils#directoryFileFilter() - */ -public class DirectoryFileFilter extends AbstractFileFilter implements Serializable { - - /** - * Singleton instance of directory filter. - * @since 1.3 - */ - public static final IOFileFilter DIRECTORY = new DirectoryFileFilter(); - /** - * Singleton instance of directory filter. - * Please use the identical DirectoryFileFilter.DIRECTORY constant. - * The new name is more JDK 1.5 friendly as it doesn't clash with other - * values when using static imports. - */ - public static final IOFileFilter INSTANCE = DIRECTORY; - - /** - * Restrictive consructor. - */ - protected DirectoryFileFilter() { - } - - /** - * Checks to see if the file is a directory. - * - * @param file the File to check - * @return true if the file is a directory - */ - @Override - public boolean accept(File file) { - return file.isDirectory(); - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/filefilter/FileFileFilter.java b/apacheandroid/src/main/java/org/apache/commons/io/filefilter/FileFileFilter.java deleted file mode 100644 index 9a9a5208a..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/filefilter/FileFileFilter.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.filefilter; - -import java.io.File; -import java.io.Serializable; - -/** - * This filter accepts Files that are files (not directories). - *

- * For example, here is how to print out a list of the real files - * within the current directory: - * - *

- * File dir = new File(".");
- * String[] files = dir.list( FileFileFilter.FILE );
- * for ( int i = 0; i < files.length; i++ ) {
- *     System.out.println(files[i]);
- * }
- * 
- * - * @since 1.3 - * @version $Id: FileFileFilter.java 1304052 2012-03-22 20:55:29Z ggregory $ - * @see FileFilterUtils#fileFileFilter() - */ -public class FileFileFilter extends AbstractFileFilter implements Serializable { - - /** Singleton instance of file filter */ - public static final IOFileFilter FILE = new FileFileFilter(); - - /** - * Restrictive consructor. - */ - protected FileFileFilter() { - } - - /** - * Checks to see if the file is a file. - * - * @param file the File to check - * @return true if the file is a file - */ - @Override - public boolean accept(File file) { - return file.isFile(); - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/filefilter/FileFilterUtils.java b/apacheandroid/src/main/java/org/apache/commons/io/filefilter/FileFilterUtils.java deleted file mode 100644 index 93fbfaa20..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/filefilter/FileFilterUtils.java +++ /dev/null @@ -1,358 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.filefilter; - -import java.io.File; -import java.io.FileFilter; -import java.io.FilenameFilter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.commons.io.IOCase; - -/** - * Useful utilities for working with file filters. It provides access to all - * file filter implementations in this package so you don't have to import - * every class you use. - * - * @since 1.0 - * @version $Id: FileFilterUtils.java 1304052 2012-03-22 20:55:29Z ggregory $ - */ -public class FileFilterUtils { - - /** - * FileFilterUtils is not normally instantiated. - */ - public FileFilterUtils() { - } - - //----------------------------------------------------------------------- - - /** - *

- * Applies an {@link IOFileFilter} to the provided {@link File} - * objects. The resulting array is a subset of the original file list that - * matches the provided filter. - *

- * - *

- * The {@link Set} returned by this method is not guaranteed to be thread safe. - *

- * - *
-     * Set<File> allFiles = ...
-     * Set<File> javaFiles = FileFilterUtils.filterSet(allFiles,
-     *     FileFilterUtils.suffixFileFilter(".java"));
-     * 
- * @param filter the filter to apply to the set of files. - * @param files the array of files to apply the filter to. - * - * @return a subset of files that is accepted by the - * file filter. - * @throws IllegalArgumentException if the filter is null - * or files contains a null value. - * - * @since 2.0 - */ - public static File[] filter(IOFileFilter filter, File... files) { - if (filter == null) { - throw new IllegalArgumentException("file filter is null"); - } - if (files == null) { - return new File[0]; - } - List acceptedFiles = new ArrayList(); - for (File file : files) { - if (file == null) { - throw new IllegalArgumentException("file array contains null"); - } - if (filter.accept(file)) { - acceptedFiles.add(file); - } - } - return acceptedFiles.toArray(new File[acceptedFiles.size()]); - } - - /** - *

- * Applies an {@link IOFileFilter} to the provided {@link File} - * objects. The resulting array is a subset of the original file list that - * matches the provided filter. - *

- * - *

- * The {@link Set} returned by this method is not guaranteed to be thread safe. - *

- * - *
-     * Set<File> allFiles = ...
-     * Set<File> javaFiles = FileFilterUtils.filterSet(allFiles,
-     *     FileFilterUtils.suffixFileFilter(".java"));
-     * 
- * @param filter the filter to apply to the set of files. - * @param files the array of files to apply the filter to. - * - * @return a subset of files that is accepted by the - * file filter. - * @throws IllegalArgumentException if the filter is null - * or files contains a null value. - * - * @since 2.0 - */ - public static File[] filter(IOFileFilter filter, Iterable files) { - List acceptedFiles = filterList(filter, files); - return acceptedFiles.toArray(new File[acceptedFiles.size()]); - } - - /** - *

- * Applies an {@link IOFileFilter} to the provided {@link File} - * objects. The resulting list is a subset of the original files that - * matches the provided filter. - *

- * - *

- * The {@link List} returned by this method is not guaranteed to be thread safe. - *

- * - *
-     * List<File> filesAndDirectories = ...
-     * List<File> directories = FileFilterUtils.filterList(filesAndDirectories,
-     *     FileFilterUtils.directoryFileFilter());
-     * 
- * @param filter the filter to apply to each files in the list. - * @param files the collection of files to apply the filter to. - * - * @return a subset of files that is accepted by the - * file filter. - * @throws IllegalArgumentException if the filter is null - * or files contains a null value. - * @since 2.0 - */ - public static List filterList(IOFileFilter filter, Iterable files) { - return filter(filter, files, new ArrayList()); - } - - /** - *

- * Applies an {@link IOFileFilter} to the provided {@link File} - * objects. The resulting list is a subset of the original files that - * matches the provided filter. - *

- * - *

- * The {@link List} returned by this method is not guaranteed to be thread safe. - *

- * - *
-     * List<File> filesAndDirectories = ...
-     * List<File> directories = FileFilterUtils.filterList(filesAndDirectories,
-     *     FileFilterUtils.directoryFileFilter());
-     * 
- * @param filter the filter to apply to each files in the list. - * @param files the collection of files to apply the filter to. - * - * @return a subset of files that is accepted by the - * file filter. - * @throws IllegalArgumentException if the filter is null - * or files contains a null value. - * @since 2.0 - */ - public static List filterList(IOFileFilter filter, File... files) { - File[] acceptedFiles = filter(filter, files); - return Arrays.asList(acceptedFiles); - } - - /** - *

- * Applies an {@link IOFileFilter} to the provided {@link File} - * objects. The resulting set is a subset of the original file list that - * matches the provided filter. - *

- * - *

- * The {@link Set} returned by this method is not guaranteed to be thread safe. - *

- * - *
-     * Set<File> allFiles = ...
-     * Set<File> javaFiles = FileFilterUtils.filterSet(allFiles,
-     *     FileFilterUtils.suffixFileFilter(".java"));
-     * 
- * @param filter the filter to apply to the set of files. - * @param files the collection of files to apply the filter to. - * - * @return a subset of files that is accepted by the - * file filter. - * @throws IllegalArgumentException if the filter is null - * or files contains a null value. - * - * @since 2.0 - */ - public static Set filterSet(IOFileFilter filter, File... files) { - File[] acceptedFiles = filter(filter, files); - return new HashSet(Arrays.asList(acceptedFiles)); - } - - /** - *

- * Applies an {@link IOFileFilter} to the provided {@link File} - * objects. The resulting set is a subset of the original file list that - * matches the provided filter. - *

- * - *

- * The {@link Set} returned by this method is not guaranteed to be thread safe. - *

- * - *
-     * Set<File> allFiles = ...
-     * Set<File> javaFiles = FileFilterUtils.filterSet(allFiles,
-     *     FileFilterUtils.suffixFileFilter(".java"));
-     * 
- * @param filter the filter to apply to the set of files. - * @param files the collection of files to apply the filter to. - * - * @return a subset of files that is accepted by the - * file filter. - * @throws IllegalArgumentException if the filter is null - * or files contains a null value. - * - * @since 2.0 - */ - public static Set filterSet(IOFileFilter filter, Iterable files) { - return filter(filter, files, new HashSet()); - } - - /** - *

- * Applies an {@link IOFileFilter} to the provided {@link File} - * objects and appends the accepted files to the other supplied collection. - *

- * - *
-     * List<File> files = ...
-     * List<File> directories = FileFilterUtils.filterList(files,
-     *     FileFilterUtils.sizeFileFilter(FileUtils.FIFTY_MB), 
-     *         new ArrayList<File>());
-     * 
- * @param filter the filter to apply to the collection of files. - * @param files the collection of files to apply the filter to. - * @param acceptedFiles the list of files to add accepted files to. - * - * @param the type of the file collection. - * @return a subset of files that is accepted by the - * file filter. - * @throws IllegalArgumentException if the filter is null - * or files contains a null value. - */ - private static > T filter(IOFileFilter filter, - Iterable files, T acceptedFiles) { - if (filter == null) { - throw new IllegalArgumentException("file filter is null"); - } - if (files != null) { - for (File file : files) { - if (file == null) { - throw new IllegalArgumentException("file collection contains null"); - } - if (filter.accept(file)) { - acceptedFiles.add(file); - } - } - } - return acceptedFiles; - } - - - /** - * Returns a filter that returns true if the filename matches the specified text. - * - * @param name the filename - * @return a name checking filter - * @see NameFileFilter - */ - public static IOFileFilter nameFileFilter(String name) { - return new NameFileFilter(name); - } - - /** - * Returns a filter that returns true if the filename matches the specified text. - * - * @param name the filename - * @param caseSensitivity how to handle case sensitivity, null means case-sensitive - * @return a name checking filter - * @see NameFileFilter - * @since 2.0 - */ - public static IOFileFilter nameFileFilter(String name, IOCase caseSensitivity) { - return new NameFileFilter(name, caseSensitivity); - } - - /** - * Returns a filter that checks if the file is a directory. - * - * @return file filter that accepts only directories and not files - * @see DirectoryFileFilter#DIRECTORY - */ - public static IOFileFilter directoryFileFilter() { - return DirectoryFileFilter.DIRECTORY; - } - - /** - * Returns a filter that checks if the file is a file (and not a directory). - * - * @return file filter that accepts only files and not directories - * @see FileFileFilter#FILE - */ - public static IOFileFilter fileFileFilter() { - return FileFileFilter.FILE; - } - - - - /** - * Create a List of file filters. - * - * @param filters The file filters - * @return The list of file filters - * @throws IllegalArgumentException if the filters are null or contain a - * null value. - * @since 2.0 - */ - public static List toList(IOFileFilter... filters) { - if (filters == null) { - throw new IllegalArgumentException("The filters must not be null"); - } - List list = new ArrayList(filters.length); - for (int i = 0; i < filters.length; i++) { - if (filters[i] == null) { - throw new IllegalArgumentException("The filter[" + i + "] is null"); - } - list.add(filters[i]); - } - return list; - } - - - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/filefilter/IOFileFilter.java b/apacheandroid/src/main/java/org/apache/commons/io/filefilter/IOFileFilter.java deleted file mode 100644 index 299495b43..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/filefilter/IOFileFilter.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.filefilter; - -import java.io.File; -import java.io.FileFilter; -import java.io.FilenameFilter; - -/** - * An interface which brings the FileFilter and FilenameFilter - * interfaces together. - * - * @since 1.0 - * @version $Id: IOFileFilter.java 1304052 2012-03-22 20:55:29Z ggregory $ - */ -public interface IOFileFilter extends FileFilter, FilenameFilter { - - /** - * Checks to see if the File should be accepted by this filter. - *

- * Defined in {@link java.io.FileFilter}. - * - * @param file the File to check - * @return true if this file matches the test - */ - boolean accept(File file); - - /** - * Checks to see if the File should be accepted by this filter. - *

- * Defined in {@link java.io.FilenameFilter}. - * - * @param dir the directory File to check - * @param name the filename within the directory to check - * @return true if this file matches the test - */ - boolean accept(File dir, String name); - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/filefilter/NameFileFilter.java b/apacheandroid/src/main/java/org/apache/commons/io/filefilter/NameFileFilter.java deleted file mode 100644 index 0419582fc..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/filefilter/NameFileFilter.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.filefilter; - -import java.io.File; -import java.io.Serializable; -import java.util.List; - -import org.apache.commons.io.IOCase; - -/** - * Filters filenames for a certain name. - *

- * For example, to print all files and directories in the - * current directory whose name is Test: - * - *

- * File dir = new File(".");
- * String[] files = dir.list( new NameFileFilter("Test") );
- * for ( int i = 0; i < files.length; i++ ) {
- *     System.out.println(files[i]);
- * }
- * 
- * - * @since 1.0 - * @version $Id: NameFileFilter.java 1304058 2012-03-22 21:02:43Z sebb $ - * @see FileFilterUtils#nameFileFilter(String) - * @see FileFilterUtils#nameFileFilter(String, IOCase) - */ -public class NameFileFilter extends AbstractFileFilter implements Serializable { - - /** The filenames to search for */ - private final String[] names; - /** Whether the comparison is case sensitive. */ - private final IOCase caseSensitivity; - - /** - * Constructs a new case-sensitive name file filter for a single name. - * - * @param name the name to allow, must not be null - * @throws IllegalArgumentException if the name is null - */ - public NameFileFilter(String name) { - this(name, null); - } - - /** - * Construct a new name file filter specifying case-sensitivity. - * - * @param name the name to allow, must not be null - * @param caseSensitivity how to handle case sensitivity, null means case-sensitive - * @throws IllegalArgumentException if the name is null - */ - public NameFileFilter(String name, IOCase caseSensitivity) { - if (name == null) { - throw new IllegalArgumentException("The wildcard must not be null"); - } - this.names = new String[] {name}; - this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; - } - - /** - * Constructs a new case-sensitive name file filter for an array of names. - *

- * The array is not cloned, so could be changed after constructing the - * instance. This would be inadvisable however. - * - * @param names the names to allow, must not be null - * @throws IllegalArgumentException if the names array is null - */ - public NameFileFilter(String[] names) { - this(names, null); - } - - /** - * Constructs a new name file filter for an array of names specifying case-sensitivity. - *

- * The array is not cloned, so could be changed after constructing the - * instance. This would be inadvisable however. - * - * @param names the names to allow, must not be null - * @param caseSensitivity how to handle case sensitivity, null means case-sensitive - * @throws IllegalArgumentException if the names array is null - */ - public NameFileFilter(String[] names, IOCase caseSensitivity) { - if (names == null) { - throw new IllegalArgumentException("The array of names must not be null"); - } - this.names = new String[names.length]; - System.arraycopy(names, 0, this.names, 0, names.length); - this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; - } - - /** - * Constructs a new case-sensitive name file filter for a list of names. - * - * @param names the names to allow, must not be null - * @throws IllegalArgumentException if the name list is null - * @throws ClassCastException if the list does not contain Strings - */ - public NameFileFilter(List names) { - this(names, null); - } - - /** - * Constructs a new name file filter for a list of names specifying case-sensitivity. - * - * @param names the names to allow, must not be null - * @param caseSensitivity how to handle case sensitivity, null means case-sensitive - * @throws IllegalArgumentException if the name list is null - * @throws ClassCastException if the list does not contain Strings - */ - public NameFileFilter(List names, IOCase caseSensitivity) { - if (names == null) { - throw new IllegalArgumentException("The list of names must not be null"); - } - this.names = names.toArray(new String[names.size()]); - this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; - } - - //----------------------------------------------------------------------- - /** - * Checks to see if the filename matches. - * - * @param file the File to check - * @return true if the filename matches - */ - @Override - public boolean accept(File file) { - String name = file.getName(); - for (String name2 : this.names) { - if (caseSensitivity.checkEquals(name, name2)) { - return true; - } - } - return false; - } - - /** - * Checks to see if the filename matches. - * - * @param dir the File directory (ignored) - * @param name the filename - * @return true if the filename matches - */ - @Override - public boolean accept(File dir, String name) { - for (String name2 : names) { - if (caseSensitivity.checkEquals(name, name2)) { - return true; - } - } - return false; - } - - /** - * Provide a String representaion of this file filter. - * - * @return a String representaion - */ - @Override - public String toString() { - StringBuilder buffer = new StringBuilder(); - buffer.append(super.toString()); - buffer.append("("); - if (names != null) { - for (int i = 0; i < names.length; i++) { - if (i > 0) { - buffer.append(","); - } - buffer.append(names[i]); - } - } - buffer.append(")"); - return buffer.toString(); - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/input/CharSequenceInputStream.java b/apacheandroid/src/main/java/org/apache/commons/io/input/CharSequenceInputStream.java deleted file mode 100644 index e2955326b..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/input/CharSequenceInputStream.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.io.input; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.CoderResult; -import java.nio.charset.CodingErrorAction; - -/** - * {@link InputStream} implementation that can read from String, StringBuffer, - * StringBuilder or CharBuffer. - *

- * Note: Supports {@link #mark(int)} and {@link #reset()}. - * - * @since 2.2 - */ -public class CharSequenceInputStream extends InputStream { - - private final CharsetEncoder encoder; - private final CharBuffer cbuf; - private final ByteBuffer bbuf; - - private int mark; - - /** - * Constructor. - * - * @param s the input character sequence - * @param charset the character set name to use - * @param bufferSize the buffer size to use. - */ - public CharSequenceInputStream(final CharSequence s, final Charset charset, int bufferSize) { - super(); - this.encoder = charset.newEncoder() - .onMalformedInput(CodingErrorAction.REPLACE) - .onUnmappableCharacter(CodingErrorAction.REPLACE); - this.bbuf = ByteBuffer.allocate(bufferSize); - this.bbuf.flip(); - this.cbuf = CharBuffer.wrap(s); - this.mark = -1; - } - - /** - * Constructor, calls {@link #CharSequenceInputStream(CharSequence, Charset, int)}. - * - * @param s the input character sequence - * @param charset the character set name to use - * @param bufferSize the buffer size to use. - */ - public CharSequenceInputStream(final CharSequence s, final String charset, int bufferSize) { - this(s, Charset.forName(charset), bufferSize); - } - - /** - * Constructor, calls {@link #CharSequenceInputStream(CharSequence, Charset, int)} - * with a buffer size of 2048. - * - * @param s the input character sequence - * @param charset the character set name to use - */ - public CharSequenceInputStream(final CharSequence s, final Charset charset) { - this(s, charset, 2048); - } - - /** - * Constructor, calls {@link #CharSequenceInputStream(CharSequence, String, int)} - * with a buffer size of 2048. - * - * @param s the input character sequence - * @param charset the character set name to use - */ - public CharSequenceInputStream(final CharSequence s, final String charset) { - this(s, charset, 2048); - } - - /** - * Fills the byte output buffer from the input char buffer. - * - * @throws CharacterCodingException - * an error encoding data - */ - private void fillBuffer() throws CharacterCodingException { - this.bbuf.compact(); - CoderResult result = this.encoder.encode(this.cbuf, this.bbuf, true); - if (result.isError()) { - result.throwException(); - } - this.bbuf.flip(); - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - if (b == null) { - throw new NullPointerException("Byte array is null"); - } - if (len < 0 || (off + len) > b.length) { - throw new IndexOutOfBoundsException("Array Size=" + b.length + - ", offset=" + off + ", length=" + len); - } - if (len == 0) { - return 0; // must return 0 for zero length read - } - if (!this.bbuf.hasRemaining() && !this.cbuf.hasRemaining()) { - return -1; - } - int bytesRead = 0; - while (len > 0) { - if (this.bbuf.hasRemaining()) { - int chunk = Math.min(this.bbuf.remaining(), len); - this.bbuf.get(b, off, chunk); - off += chunk; - len -= chunk; - bytesRead += chunk; - } else { - fillBuffer(); - if (!this.bbuf.hasRemaining() && !this.cbuf.hasRemaining()) { - break; - } - } - } - return bytesRead == 0 && !this.cbuf.hasRemaining() ? -1 : bytesRead; - } - - @Override - public int read() throws IOException { - for (;;) { - if (this.bbuf.hasRemaining()) { - return this.bbuf.get() & 0xFF; - } else { - fillBuffer(); - if (!this.bbuf.hasRemaining() && !this.cbuf.hasRemaining()) { - return -1; - } - } - } - } - - @Override - public int read(byte[] b) throws IOException { - return read(b, 0, b.length); - } - - @Override - public long skip(long n) throws IOException { - int skipped = 0; - while (n > 0 && this.cbuf.hasRemaining()) { - this.cbuf.get(); - n--; - skipped++; - } - return skipped; - } - - @Override - public int available() throws IOException { - return this.cbuf.remaining(); - } - - @Override - public void close() throws IOException { - } - - /** - * {@inheritDoc} - * @param readlimit max read limit (ignored) - */ - @Override - public synchronized void mark(@SuppressWarnings("unused") int readlimit) { - this.mark = this.cbuf.position(); - } - - @Override - public synchronized void reset() throws IOException { - if (this.mark != -1) { - this.cbuf.position(this.mark); - this.mark = -1; - } - } - - @Override - public boolean markSupported() { - return true; - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/input/CharSequenceReader.java b/apacheandroid/src/main/java/org/apache/commons/io/input/CharSequenceReader.java deleted file mode 100644 index d7331a6cf..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/input/CharSequenceReader.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.input; - -import java.io.Reader; -import java.io.Serializable; - -/** - * {@link Reader} implementation that can read from String, StringBuffer, - * StringBuilder or CharBuffer. - *

- * Note: Supports {@link #mark(int)} and {@link #reset()}. - * - * @version $Id: CharSequenceReader.java 1304052 2012-03-22 20:55:29Z ggregory $ - * @since 1.4 - */ -public class CharSequenceReader extends Reader implements Serializable { - - private final CharSequence charSequence; - private int idx; - private int mark; - - /** - * Construct a new instance with the specified character sequence. - * - * @param charSequence The character sequence, may be null - */ - public CharSequenceReader(CharSequence charSequence) { - this.charSequence = charSequence != null ? charSequence : ""; - } - - /** - * Close resets the file back to the start and removes any marked position. - */ - @Override - public void close() { - idx = 0; - mark = 0; - } - - /** - * Mark the current position. - * - * @param readAheadLimit ignored - */ - @Override - public void mark(int readAheadLimit) { - mark = idx; - } - - /** - * Mark is supported (returns true). - * - * @return true - */ - @Override - public boolean markSupported() { - return true; - } - - /** - * Read a single character. - * - * @return the next character from the character sequence - * or -1 if the end has been reached. - */ - @Override - public int read() { - if (idx >= charSequence.length()) { - return -1; - } else { - return charSequence.charAt(idx++); - } - } - - /** - * Read the sepcified number of characters into the array. - * - * @param array The array to store the characters in - * @param offset The starting position in the array to store - * @param length The maximum number of characters to read - * @return The number of characters read or -1 if there are - * no more - */ - @Override - public int read(char[] array, int offset, int length) { - if (idx >= charSequence.length()) { - return -1; - } - if (array == null) { - throw new NullPointerException("Character array is missing"); - } - if (length < 0 || offset < 0 || offset + length > array.length) { - throw new IndexOutOfBoundsException("Array Size=" + array.length + - ", offset=" + offset + ", length=" + length); - } - int count = 0; - for (int i = 0; i < length; i++) { - int c = read(); - if (c == -1) { - return count; - } - array[offset + i] = (char)c; - count++; - } - return count; - } - - /** - * Reset the reader to the last marked position (or the beginning if - * mark has not been called). - */ - @Override - public void reset() { - idx = mark; - } - - /** - * Skip the specified number of characters. - * - * @param n The number of characters to skip - * @return The actual number of characters skipped - */ - @Override - public long skip(long n) { - if (n < 0) { - throw new IllegalArgumentException( - "Number of characters to skip is less than zero: " + n); - } - if (idx >= charSequence.length()) { - return -1; - } - int dest = (int)Math.min(charSequence.length(), idx + n); - int count = dest - idx; - idx = dest; - return count; - } - - /** - * Return a String representation of the underlying - * character sequence. - * - * @return The contents of the character sequence - */ - @Override - public String toString() { - return charSequence.toString(); - } -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/input/ClosedInputStream.java b/apacheandroid/src/main/java/org/apache/commons/io/input/ClosedInputStream.java deleted file mode 100644 index bd1e3ff05..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/input/ClosedInputStream.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.input; - -import java.io.InputStream; - -/** - * Closed input stream. This stream returns -1 to all attempts to read - * something from the stream. - *

- * Typically uses of this class include testing for corner cases in methods - * that accept input streams and acting as a sentinel value instead of a - * null input stream. - * - * @version $Id: ClosedInputStream.java 1304052 2012-03-22 20:55:29Z ggregory $ - * @since 1.4 - */ -public class ClosedInputStream extends InputStream { - - /** - * A singleton. - */ - public static final ClosedInputStream CLOSED_INPUT_STREAM = new ClosedInputStream(); - - /** - * Returns -1 to indicate that the stream is closed. - * - * @return always -1 - */ - @Override - public int read() { - return -1; - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/input/NullInputStream.java b/apacheandroid/src/main/java/org/apache/commons/io/input/NullInputStream.java deleted file mode 100644 index 8cf73fbe0..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/input/NullInputStream.java +++ /dev/null @@ -1,338 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.input; - -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; - -/** - * A functional, light weight {@link InputStream} that emulates - * a stream of a specified size. - *

- * This implementation provides a light weight - * object for testing with an {@link InputStream} - * where the contents don't matter. - *

- * One use case would be for testing the handling of - * large {@link InputStream} as it can emulate that - * scenario without the overhead of actually processing - * large numbers of bytes - significantly speeding up - * test execution times. - *

- * This implementation returns zero from the method that - * reads a byte and leaves the array unchanged in the read - * methods that are passed a byte array. - * If alternative data is required the processByte() and - * processBytes() methods can be implemented to generate - * data, for example: - * - *

- *  public class TestInputStream extends NullInputStream {
- *      public TestInputStream(int size) {
- *          super(size);
- *      }
- *      protected int processByte() {
- *          return ... // return required value here
- *      }
- *      protected void processBytes(byte[] bytes, int offset, int length) {
- *          for (int i = offset; i < length; i++) {
- *              bytes[i] = ... // set array value here
- *          }
- *      }
- *  }
- * 
- * - * @since 1.3 - * @version $Id: NullInputStream.java 1304052 2012-03-22 20:55:29Z ggregory $ - */ -public class NullInputStream extends InputStream { - - private final long size; - private long position; - private long mark = -1; - private long readlimit; - private boolean eof; - private final boolean throwEofException; - private final boolean markSupported; - - /** - * Create an {@link InputStream} that emulates a specified size - * which supports marking and does not throw EOFException. - * - * @param size The size of the input stream to emulate. - */ - public NullInputStream(long size) { - this(size, true, false); - } - - /** - * Create an {@link InputStream} that emulates a specified - * size with option settings. - * - * @param size The size of the input stream to emulate. - * @param markSupported Whether this instance will support - * the mark() functionality. - * @param throwEofException Whether this implementation - * will throw an {@link EOFException} or return -1 when the - * end of file is reached. - */ - public NullInputStream(long size, boolean markSupported, boolean throwEofException) { - this.size = size; - this.markSupported = markSupported; - this.throwEofException = throwEofException; - } - - /** - * Return the current position. - * - * @return the current position. - */ - public long getPosition() { - return position; - } - - /** - * Return the size this {@link InputStream} emulates. - * - * @return The size of the input stream to emulate. - */ - public long getSize() { - return size; - } - - /** - * Return the number of bytes that can be read. - * - * @return The number of bytes that can be read. - */ - @Override - public int available() { - long avail = size - position; - if (avail <= 0) { - return 0; - } else if (avail > Integer.MAX_VALUE) { - return Integer.MAX_VALUE; - } else { - return (int)avail; - } - } - - /** - * Close this input stream - resets the internal state to - * the initial values. - * - * @throws IOException If an error occurs. - */ - @Override - public void close() throws IOException { - eof = false; - position = 0; - mark = -1; - } - - /** - * Mark the current position. - * - * @param readlimit The number of bytes before this marked position - * is invalid. - * @throws UnsupportedOperationException if mark is not supported. - */ - @Override - public synchronized void mark(int readlimit) { - if (!markSupported) { - throw new UnsupportedOperationException("Mark not supported"); - } - mark = position; - this.readlimit = readlimit; - } - - /** - * Indicates whether mark is supported. - * - * @return Whether mark is supported or not. - */ - @Override - public boolean markSupported() { - return markSupported; - } - - /** - * Read a byte. - * - * @return Either The byte value returned by processByte() - * or -1 if the end of file has been reached and - * throwEofException is set to false. - * @throws EOFException if the end of file is reached and - * throwEofException is set to true. - * @throws IOException if trying to read past the end of file. - */ - @Override - public int read() throws IOException { - if (eof) { - throw new IOException("Read after end of file"); - } - if (position == size) { - return doEndOfFile(); - } - position++; - return processByte(); - } - - /** - * Read some bytes into the specified array. - * - * @param bytes The byte array to read into - * @return The number of bytes read or -1 - * if the end of file has been reached and - * throwEofException is set to false. - * @throws EOFException if the end of file is reached and - * throwEofException is set to true. - * @throws IOException if trying to read past the end of file. - */ - @Override - public int read(byte[] bytes) throws IOException { - return read(bytes, 0, bytes.length); - } - - /** - * Read the specified number bytes into an array. - * - * @param bytes The byte array to read into. - * @param offset The offset to start reading bytes into. - * @param length The number of bytes to read. - * @return The number of bytes read or -1 - * if the end of file has been reached and - * throwEofException is set to false. - * @throws EOFException if the end of file is reached and - * throwEofException is set to true. - * @throws IOException if trying to read past the end of file. - */ - @Override - public int read(byte[] bytes, int offset, int length) throws IOException { - if (eof) { - throw new IOException("Read after end of file"); - } - if (position == size) { - return doEndOfFile(); - } - position += length; - int returnLength = length; - if (position > size) { - returnLength = length - (int)(position - size); - position = size; - } - processBytes(bytes, offset, returnLength); - return returnLength; - } - - /** - * Reset the stream to the point when mark was last called. - * - * @throws UnsupportedOperationException if mark is not supported. - * @throws IOException If no position has been marked - * or the read limit has been exceed since the last position was - * marked. - */ - @Override - public synchronized void reset() throws IOException { - if (!markSupported) { - throw new UnsupportedOperationException("Mark not supported"); - } - if (mark < 0) { - throw new IOException("No position has been marked"); - } - if (position > mark + readlimit) { - throw new IOException("Marked position [" + mark + - "] is no longer valid - passed the read limit [" + - readlimit + "]"); - } - position = mark; - eof = false; - } - - /** - * Skip a specified number of bytes. - * - * @param numberOfBytes The number of bytes to skip. - * @return The number of bytes skipped or -1 - * if the end of file has been reached and - * throwEofException is set to false. - * @throws EOFException if the end of file is reached and - * throwEofException is set to true. - * @throws IOException if trying to read past the end of file. - */ - @Override - public long skip(long numberOfBytes) throws IOException { - if (eof) { - throw new IOException("Skip after end of file"); - } - if (position == size) { - return doEndOfFile(); - } - position += numberOfBytes; - long returnLength = numberOfBytes; - if (position > size) { - returnLength = numberOfBytes - (position - size); - position = size; - } - return returnLength; - } - - /** - * Return a byte value for the read() method. - *

- * This implementation returns zero. - * - * @return This implementation always returns zero. - */ - protected int processByte() { - // do nothing - overridable by subclass - return 0; - } - - /** - * Process the bytes for the read(byte[], offset, length) - * method. - *

- * This implementation leaves the byte array unchanged. - * - * @param bytes The byte array - * @param offset The offset to start at. - * @param length The number of bytes. - */ - protected void processBytes(byte[] bytes, int offset, int length) { - // do nothing - overridable by subclass - } - - /** - * Handle End of File. - * - * @return -1 if throwEofException is - * set to false - * @throws EOFException if throwEofException is set - * to true. - */ - private int doEndOfFile() throws EOFException { - eof = true; - if (throwEofException) { - throw new EOFException(); - } - return -1; - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/input/NullReader.java b/apacheandroid/src/main/java/org/apache/commons/io/input/NullReader.java deleted file mode 100644 index 4a70aff07..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/input/NullReader.java +++ /dev/null @@ -1,321 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.input; - -import java.io.EOFException; -import java.io.IOException; -import java.io.Reader; - -/** - * A functional, light weight {@link Reader} that emulates - * a reader of a specified size. - *

- * This implementation provides a light weight - * object for testing with an {@link Reader} - * where the contents don't matter. - *

- * One use case would be for testing the handling of - * large {@link Reader} as it can emulate that - * scenario without the overhead of actually processing - * large numbers of characters - significantly speeding up - * test execution times. - *

- * This implementation returns a space from the method that - * reads a character and leaves the array unchanged in the read - * methods that are passed a character array. - * If alternative data is required the processChar() and - * processChars() methods can be implemented to generate - * data, for example: - * - *

- *  public class TestReader extends NullReader {
- *      public TestReader(int size) {
- *          super(size);
- *      }
- *      protected char processChar() {
- *          return ... // return required value here
- *      }
- *      protected void processChars(char[] chars, int offset, int length) {
- *          for (int i = offset; i < length; i++) {
- *              chars[i] = ... // set array value here
- *          }
- *      }
- *  }
- * 
- * - * @since 1.3 - * @version $Id: NullReader.java 1304052 2012-03-22 20:55:29Z ggregory $ - */ -public class NullReader extends Reader { - - private final long size; - private long position; - private long mark = -1; - private long readlimit; - private boolean eof; - private final boolean throwEofException; - private final boolean markSupported; - - /** - * Create a {@link Reader} that emulates a specified size - * which supports marking and does not throw EOFException. - * - * @param size The size of the reader to emulate. - */ - public NullReader(long size) { - this(size, true, false); - } - - /** - * Create a {@link Reader} that emulates a specified - * size with option settings. - * - * @param size The size of the reader to emulate. - * @param markSupported Whether this instance will support - * the mark() functionality. - * @param throwEofException Whether this implementation - * will throw an {@link EOFException} or return -1 when the - * end of file is reached. - */ - public NullReader(long size, boolean markSupported, boolean throwEofException) { - this.size = size; - this.markSupported = markSupported; - this.throwEofException = throwEofException; - } - - /** - * Return the current position. - * - * @return the current position. - */ - public long getPosition() { - return position; - } - - /** - * Return the size this {@link Reader} emulates. - * - * @return The size of the reader to emulate. - */ - public long getSize() { - return size; - } - - /** - * Close this Reader - resets the internal state to - * the initial values. - * - * @throws IOException If an error occurs. - */ - @Override - public void close() throws IOException { - eof = false; - position = 0; - mark = -1; - } - - /** - * Mark the current position. - * - * @param readlimit The number of characters before this marked position - * is invalid. - * @throws UnsupportedOperationException if mark is not supported. - */ - @Override - public synchronized void mark(int readlimit) { - if (!markSupported) { - throw new UnsupportedOperationException("Mark not supported"); - } - mark = position; - this.readlimit = readlimit; - } - - /** - * Indicates whether mark is supported. - * - * @return Whether mark is supported or not. - */ - @Override - public boolean markSupported() { - return markSupported; - } - - /** - * Read a character. - * - * @return Either The character value returned by processChar() - * or -1 if the end of file has been reached and - * throwEofException is set to false. - * @throws EOFException if the end of file is reached and - * throwEofException is set to true. - * @throws IOException if trying to read past the end of file. - */ - @Override - public int read() throws IOException { - if (eof) { - throw new IOException("Read after end of file"); - } - if (position == size) { - return doEndOfFile(); - } - position++; - return processChar(); - } - - /** - * Read some characters into the specified array. - * - * @param chars The character array to read into - * @return The number of characters read or -1 - * if the end of file has been reached and - * throwEofException is set to false. - * @throws EOFException if the end of file is reached and - * throwEofException is set to true. - * @throws IOException if trying to read past the end of file. - */ - @Override - public int read(char[] chars) throws IOException { - return read(chars, 0, chars.length); - } - - /** - * Read the specified number characters into an array. - * - * @param chars The character array to read into. - * @param offset The offset to start reading characters into. - * @param length The number of characters to read. - * @return The number of characters read or -1 - * if the end of file has been reached and - * throwEofException is set to false. - * @throws EOFException if the end of file is reached and - * throwEofException is set to true. - * @throws IOException if trying to read past the end of file. - */ - @Override - public int read(char[] chars, int offset, int length) throws IOException { - if (eof) { - throw new IOException("Read after end of file"); - } - if (position == size) { - return doEndOfFile(); - } - position += length; - int returnLength = length; - if (position > size) { - returnLength = length - (int)(position - size); - position = size; - } - processChars(chars, offset, returnLength); - return returnLength; - } - - /** - * Reset the stream to the point when mark was last called. - * - * @throws UnsupportedOperationException if mark is not supported. - * @throws IOException If no position has been marked - * or the read limit has been exceed since the last position was - * marked. - */ - @Override - public synchronized void reset() throws IOException { - if (!markSupported) { - throw new UnsupportedOperationException("Mark not supported"); - } - if (mark < 0) { - throw new IOException("No position has been marked"); - } - if (position > mark + readlimit) { - throw new IOException("Marked position [" + mark + - "] is no longer valid - passed the read limit [" + - readlimit + "]"); - } - position = mark; - eof = false; - } - - /** - * Skip a specified number of characters. - * - * @param numberOfChars The number of characters to skip. - * @return The number of characters skipped or -1 - * if the end of file has been reached and - * throwEofException is set to false. - * @throws EOFException if the end of file is reached and - * throwEofException is set to true. - * @throws IOException if trying to read past the end of file. - */ - @Override - public long skip(long numberOfChars) throws IOException { - if (eof) { - throw new IOException("Skip after end of file"); - } - if (position == size) { - return doEndOfFile(); - } - position += numberOfChars; - long returnLength = numberOfChars; - if (position > size) { - returnLength = numberOfChars - (position - size); - position = size; - } - return returnLength; - } - - /** - * Return a character value for the read() method. - *

- * This implementation returns zero. - * - * @return This implementation always returns zero. - */ - protected int processChar() { - // do nothing - overridable by subclass - return 0; - } - - /** - * Process the characters for the read(char[], offset, length) - * method. - *

- * This implementation leaves the character array unchanged. - * - * @param chars The character array - * @param offset The offset to start at. - * @param length The number of characters. - */ - protected void processChars(char[] chars, int offset, int length) { - // do nothing - overridable by subclass - } - - /** - * Handle End of File. - * - * @return -1 if throwEofException is - * set to false - * @throws EOFException if throwEofException is set - * to true. - */ - private int doEndOfFile() throws EOFException { - eof = true; - if (throwEofException) { - throw new EOFException(); - } - return -1; - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/input/ReaderInputStream.java b/apacheandroid/src/main/java/org/apache/commons/io/input/ReaderInputStream.java deleted file mode 100644 index 9d6cc0e3a..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/input/ReaderInputStream.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.input; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.Charset; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.CoderResult; -import java.nio.charset.CodingErrorAction; - -/** - * {@link InputStream} implementation that reads a character stream from a {@link Reader} - * and transforms it to a byte stream using a specified charset encoding. The stream - * is transformed using a {@link CharsetEncoder} object, guaranteeing that all charset - * encodings supported by the JRE are handled correctly. In particular for charsets such as - * UTF-16, the implementation ensures that one and only one byte order marker - * is produced. - *

- * Since in general it is not possible to predict the number of characters to be read from the - * {@link Reader} to satisfy a read request on the {@link ReaderInputStream}, all reads from - * the {@link Reader} are buffered. There is therefore no well defined correlation - * between the current position of the {@link Reader} and that of the {@link ReaderInputStream}. - * This also implies that in general there is no need to wrap the underlying {@link Reader} - * in a {@link java.io.BufferedReader}. - *

- * {@link ReaderInputStream} implements the inverse transformation of {@link java.io.InputStreamReader}; - * in the following example, reading from in2 would return the same byte - * sequence as reading from in (provided that the initial byte sequence is legal - * with respect to the charset encoding): - *

- * InputStream in = ...
- * Charset cs = ...
- * InputStreamReader reader = new InputStreamReader(in, cs);
- * ReaderInputStream in2 = new ReaderInputStream(reader, cs);
- * {@link ReaderInputStream} implements the same transformation as {@link java.io.OutputStreamWriter}, - * except that the control flow is reversed: both classes transform a character stream - * into a byte stream, but {@link java.io.OutputStreamWriter} pushes data to the underlying stream, - * while {@link ReaderInputStream} pulls it from the underlying stream. - *

- * Note that while there are use cases where there is no alternative to using - * this class, very often the need to use this class is an indication of a flaw - * in the design of the code. This class is typically used in situations where an existing - * API only accepts an {@link InputStream}, but where the most natural way to produce the data - * is as a character stream, i.e. by providing a {@link Reader} instance. An example of a situation - * where this problem may appear is when implementing the {@link javax.activation.DataSource} - * interface from the Java Activation Framework. - *

- * Given the fact that the {@link Reader} class doesn't provide any way to predict whether the next - * read operation will block or not, it is not possible to provide a meaningful - * implementation of the {@link InputStream#available()} method. A call to this method - * will always return 0. Also, this class doesn't support {@link InputStream#mark(int)}. - *

- * Instances of {@link ReaderInputStream} are not thread safe. - * - * @see org.apache.commons.io.output.WriterOutputStream - * - * @since 2.0 - */ -public class ReaderInputStream extends InputStream { - private static final int DEFAULT_BUFFER_SIZE = 1024; - - private final Reader reader; - private final CharsetEncoder encoder; - - /** - * CharBuffer used as input for the decoder. It should be reasonably - * large as we read data from the underlying Reader into this buffer. - */ - private final CharBuffer encoderIn; - - /** - * ByteBuffer used as output for the decoder. This buffer can be small - * as it is only used to transfer data from the decoder to the - * buffer provided by the caller. - */ - private final ByteBuffer encoderOut; - - private CoderResult lastCoderResult; - private boolean endOfInput; - - /** - * Construct a new {@link ReaderInputStream}. - * - * @param reader the target {@link Reader} - * @param encoder the charset encoder - * @since 2.1 - */ - public ReaderInputStream(Reader reader, CharsetEncoder encoder) { - this(reader, encoder, DEFAULT_BUFFER_SIZE); - } - - /** - * Construct a new {@link ReaderInputStream}. - * - * @param reader the target {@link Reader} - * @param encoder the charset encoder - * @param bufferSize the size of the input buffer in number of characters - * @since 2.1 - */ - public ReaderInputStream(Reader reader, CharsetEncoder encoder, int bufferSize) { - this.reader = reader; - this.encoder = encoder; - this.encoderIn = CharBuffer.allocate(bufferSize); - this.encoderIn.flip(); - this.encoderOut = ByteBuffer.allocate(128); - this.encoderOut.flip(); - } - - /** - * Construct a new {@link ReaderInputStream}. - * - * @param reader the target {@link Reader} - * @param charset the charset encoding - * @param bufferSize the size of the input buffer in number of characters - */ - public ReaderInputStream(Reader reader, Charset charset, int bufferSize) { - this(reader, - charset.newEncoder() - .onMalformedInput(CodingErrorAction.REPLACE) - .onUnmappableCharacter(CodingErrorAction.REPLACE), - bufferSize); - } - - /** - * Construct a new {@link ReaderInputStream} with a default input buffer size of - * 1024 characters. - * - * @param reader the target {@link Reader} - * @param charset the charset encoding - */ - public ReaderInputStream(Reader reader, Charset charset) { - this(reader, charset, DEFAULT_BUFFER_SIZE); - } - - /** - * Construct a new {@link ReaderInputStream}. - * - * @param reader the target {@link Reader} - * @param charsetName the name of the charset encoding - * @param bufferSize the size of the input buffer in number of characters - */ - public ReaderInputStream(Reader reader, String charsetName, int bufferSize) { - this(reader, Charset.forName(charsetName), bufferSize); - } - - /** - * Construct a new {@link ReaderInputStream} with a default input buffer size of - * 1024 characters. - * - * @param reader the target {@link Reader} - * @param charsetName the name of the charset encoding - */ - public ReaderInputStream(Reader reader, String charsetName) { - this(reader, charsetName, DEFAULT_BUFFER_SIZE); - } - - /** - * Construct a new {@link ReaderInputStream} that uses the default character encoding - * with a default input buffer size of 1024 characters. - * - * @param reader the target {@link Reader} - */ - public ReaderInputStream(Reader reader) { - this(reader, Charset.defaultCharset()); - } - - /** - * Fills the internal char buffer from the reader. - * - * @throws IOException - * If an I/O error occurs - */ - private void fillBuffer() throws IOException { - if (!endOfInput && (lastCoderResult == null || lastCoderResult.isUnderflow())) { - encoderIn.compact(); - int position = encoderIn.position(); - // We don't use Reader#read(CharBuffer) here because it is more efficient - // to write directly to the underlying char array (the default implementation - // copies data to a temporary char array). - int c = reader.read(encoderIn.array(), position, encoderIn.remaining()); - if (c == -1) { - endOfInput = true; - } else { - encoderIn.position(position+c); - } - encoderIn.flip(); - } - encoderOut.compact(); - lastCoderResult = encoder.encode(encoderIn, encoderOut, endOfInput); - encoderOut.flip(); - } - - /** - * Read the specified number of bytes into an array. - * - * @param b the byte array to read into - * @param off the offset to start reading bytes into - * @param len the number of bytes to read - * @return the number of bytes read or -1 - * if the end of the stream has been reached - * @throws IOException if an I/O error occurs - */ - @Override - public int read(byte[] b, int off, int len) throws IOException { - if (b == null) { - throw new NullPointerException("Byte array must not be null"); - } - if (len < 0 || off < 0 || (off + len) > b.length) { - throw new IndexOutOfBoundsException("Array Size=" + b.length + - ", offset=" + off + ", length=" + len); - } - int read = 0; - if (len == 0) { - return 0; // Always return 0 if len == 0 - } - while (len > 0) { - if (encoderOut.hasRemaining()) { - int c = Math.min(encoderOut.remaining(), len); - encoderOut.get(b, off, c); - off += c; - len -= c; - read += c; - } else { - fillBuffer(); - if (endOfInput && !encoderOut.hasRemaining()) { - break; - } - } - } - return read == 0 && endOfInput ? -1 : read; - } - - /** - * Read the specified number of bytes into an array. - * - * @param b the byte array to read into - * @return the number of bytes read or -1 - * if the end of the stream has been reached - * @throws IOException if an I/O error occurs - */ - @Override - public int read(byte[] b) throws IOException { - return read(b, 0, b.length); - } - - /** - * Read a single byte. - * - * @return either the byte read or -1 if the end of the stream - * has been reached - * @throws IOException if an I/O error occurs - */ - @Override - public int read() throws IOException { - for (;;) { - if (encoderOut.hasRemaining()) { - return encoderOut.get() & 0xFF; - } else { - fillBuffer(); - if (endOfInput && !encoderOut.hasRemaining()) { - return -1; - } - } - } - } - - /** - * Close the stream. This method will cause the underlying {@link Reader} - * to be closed. - * @throws IOException if an I/O error occurs - */ - @Override - public void close() throws IOException { - reader.close(); - } -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/output/ByteArrayOutputStream.java b/apacheandroid/src/main/java/org/apache/commons/io/output/ByteArrayOutputStream.java deleted file mode 100644 index 27825f719..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/output/ByteArrayOutputStream.java +++ /dev/null @@ -1,359 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.output; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.SequenceInputStream; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.apache.commons.io.input.ClosedInputStream; - -/** - * This class implements an output stream in which the data is - * written into a byte array. The buffer automatically grows as data - * is written to it. - *

- * The data can be retrieved using toByteArray() and - * toString(). - *

- * Closing a ByteArrayOutputStream has no effect. The methods in - * this class can be called after the stream has been closed without - * generating an IOException. - *

- * This is an alternative implementation of the {@link java.io.ByteArrayOutputStream} - * class. The original implementation only allocates 32 bytes at the beginning. - * As this class is designed for heavy duty it starts at 1024 bytes. In contrast - * to the original it doesn't reallocate the whole memory block but allocates - * additional buffers. This way no buffers need to be garbage collected and - * the contents don't have to be copied to the new buffer. This class is - * designed to behave exactly like the original. The only exception is the - * deprecated toString(int) method that has been ignored. - * - * @version $Id: ByteArrayOutputStream.java 1304052 2012-03-22 20:55:29Z ggregory $ - */ -public class ByteArrayOutputStream extends OutputStream { - - /** A singleton empty byte array. */ - private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; - - /** The list of buffers, which grows and never reduces. */ - private final List buffers = new ArrayList(); - /** The index of the current buffer. */ - private int currentBufferIndex; - /** The total count of bytes in all the filled buffers. */ - private int filledBufferSum; - /** The current buffer. */ - private byte[] currentBuffer; - /** The total count of bytes written. */ - private int count; - - /** - * Creates a new byte array output stream. The buffer capacity is - * initially 1024 bytes, though its size increases if necessary. - */ - public ByteArrayOutputStream() { - this(1024); - } - - /** - * Creates a new byte array output stream, with a buffer capacity of - * the specified size, in bytes. - * - * @param size the initial size - * @throws IllegalArgumentException if size is negative - */ - public ByteArrayOutputStream(int size) { - if (size < 0) { - throw new IllegalArgumentException( - "Negative initial size: " + size); - } - synchronized (this) { - needNewBuffer(size); - } - } - - /** - * Makes a new buffer available either by allocating - * a new one or re-cycling an existing one. - * - * @param newcount the size of the buffer if one is created - */ - private void needNewBuffer(int newcount) { - if (currentBufferIndex < buffers.size() - 1) { - //Recycling old buffer - filledBufferSum += currentBuffer.length; - - currentBufferIndex++; - currentBuffer = buffers.get(currentBufferIndex); - } else { - //Creating new buffer - int newBufferSize; - if (currentBuffer == null) { - newBufferSize = newcount; - filledBufferSum = 0; - } else { - newBufferSize = Math.max( - currentBuffer.length << 1, - newcount - filledBufferSum); - filledBufferSum += currentBuffer.length; - } - - currentBufferIndex++; - currentBuffer = new byte[newBufferSize]; - buffers.add(currentBuffer); - } - } - - /** - * Write the bytes to byte array. - * @param b the bytes to write - * @param off The start offset - * @param len The number of bytes to write - */ - @Override - public void write(byte[] b, int off, int len) { - if ((off < 0) - || (off > b.length) - || (len < 0) - || ((off + len) > b.length) - || ((off + len) < 0)) { - throw new IndexOutOfBoundsException(); - } else if (len == 0) { - return; - } - synchronized (this) { - int newcount = count + len; - int remaining = len; - int inBufferPos = count - filledBufferSum; - while (remaining > 0) { - int part = Math.min(remaining, currentBuffer.length - inBufferPos); - System.arraycopy(b, off + len - remaining, currentBuffer, inBufferPos, part); - remaining -= part; - if (remaining > 0) { - needNewBuffer(newcount); - inBufferPos = 0; - } - } - count = newcount; - } - } - - /** - * Write a byte to byte array. - * @param b the byte to write - */ - @Override - public synchronized void write(int b) { - int inBufferPos = count - filledBufferSum; - if (inBufferPos == currentBuffer.length) { - needNewBuffer(count + 1); - inBufferPos = 0; - } - currentBuffer[inBufferPos] = (byte) b; - count++; - } - - /** - * Writes the entire contents of the specified input stream to this - * byte stream. Bytes from the input stream are read directly into the - * internal buffers of this streams. - * - * @param in the input stream to read from - * @return total number of bytes read from the input stream - * (and written to this stream) - * @throws IOException if an I/O error occurs while reading the input stream - * @since 1.4 - */ - public synchronized int write(InputStream in) throws IOException { - int readCount = 0; - int inBufferPos = count - filledBufferSum; - int n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos); - while (n != -1) { - readCount += n; - inBufferPos += n; - count += n; - if (inBufferPos == currentBuffer.length) { - needNewBuffer(currentBuffer.length); - inBufferPos = 0; - } - n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos); - } - return readCount; - } - - /** - * Return the current size of the byte array. - * @return the current size of the byte array - */ - public synchronized int size() { - return count; - } - - /** - * Closing a ByteArrayOutputStream has no effect. The methods in - * this class can be called after the stream has been closed without - * generating an IOException. - * - * @throws IOException never (this method should not declare this exception - * but it has to now due to backwards compatability) - */ - @Override - public void close() throws IOException { - //nop - } - - /** - * @see java.io.ByteArrayOutputStream#reset() - */ - public synchronized void reset() { - count = 0; - filledBufferSum = 0; - currentBufferIndex = 0; - currentBuffer = buffers.get(currentBufferIndex); - } - - /** - * Writes the entire contents of this byte stream to the - * specified output stream. - * - * @param out the output stream to write to - * @throws IOException if an I/O error occurs, such as if the stream is closed - * @see java.io.ByteArrayOutputStream#writeTo(OutputStream) - */ - public synchronized void writeTo(OutputStream out) throws IOException { - int remaining = count; - for (byte[] buf : buffers) { - int c = Math.min(buf.length, remaining); - out.write(buf, 0, c); - remaining -= c; - if (remaining == 0) { - break; - } - } - } - - /** - * Fetches entire contents of an InputStream and represent - * same data as result InputStream. - *

- * This method is useful where, - *

    - *
  • Source InputStream is slow.
  • - *
  • It has network resources associated, so we cannot keep it open for - * long time.
  • - *
  • It has network timeout associated.
  • - *
- * It can be used in favor of {@link #toByteArray()}, since it - * avoids unnecessary allocation and copy of byte[].
- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input Stream to be fully buffered. - * @return A fully buffered stream. - * @throws IOException if an I/O error occurs - * @since 2.0 - */ - public static InputStream toBufferedInputStream(InputStream input) - throws IOException { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - output.write(input); - return output.toBufferedInputStream(); - } - - /** - * Gets the current contents of this byte stream as a Input Stream. The - * returned stream is backed by buffers of this stream, - * avoiding memory allocation and copy, thus saving space and time.
- * - * @return the current contents of this output stream. - * @see java.io.ByteArrayOutputStream#toByteArray() - * @see #reset() - * @since 2.0 - */ - private InputStream toBufferedInputStream() { - int remaining = count; - if (remaining == 0) { - return new ClosedInputStream(); - } - List list = new ArrayList(buffers.size()); - for (byte[] buf : buffers) { - int c = Math.min(buf.length, remaining); - list.add(new ByteArrayInputStream(buf, 0, c)); - remaining -= c; - if (remaining == 0) { - break; - } - } - return new SequenceInputStream(Collections.enumeration(list)); - } - - /** - * Gets the curent contents of this byte stream as a byte array. - * The result is independent of this stream. - * - * @return the current contents of this output stream, as a byte array - * @see java.io.ByteArrayOutputStream#toByteArray() - */ - public synchronized byte[] toByteArray() { - int remaining = count; - if (remaining == 0) { - return EMPTY_BYTE_ARRAY; - } - byte newbuf[] = new byte[remaining]; - int pos = 0; - for (byte[] buf : buffers) { - int c = Math.min(buf.length, remaining); - System.arraycopy(buf, 0, newbuf, pos, c); - pos += c; - remaining -= c; - if (remaining == 0) { - break; - } - } - return newbuf; - } - - /** - * Gets the curent contents of this byte stream as a string. - * @return the contents of the byte array as a String - * @see java.io.ByteArrayOutputStream#toString() - */ - @Override - public String toString() { - return new String(toByteArray()); - } - - /** - * Gets the curent contents of this byte stream as a string - * using the specified encoding. - * - * @param enc the name of the character encoding - * @return the string converted from the byte array - * @throws UnsupportedEncodingException if the encoding is not supported - * @see java.io.ByteArrayOutputStream#toString(String) - */ - public String toString(String enc) throws UnsupportedEncodingException { - return new String(toByteArray(), enc); - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/output/ClosedOutputStream.java b/apacheandroid/src/main/java/org/apache/commons/io/output/ClosedOutputStream.java deleted file mode 100644 index d8e48eb01..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/output/ClosedOutputStream.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.output; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * Closed output stream. This stream throws an exception on all attempts to - * write something to the stream. - *

- * Typically uses of this class include testing for corner cases in methods - * that accept an output stream and acting as a sentinel value instead of - * a null output stream. - * - * @version $Id: ClosedOutputStream.java 1304052 2012-03-22 20:55:29Z ggregory $ - * @since 1.4 - */ -public class ClosedOutputStream extends OutputStream { - - /** - * A singleton. - */ - public static final ClosedOutputStream CLOSED_OUTPUT_STREAM = new ClosedOutputStream(); - - /** - * Throws an {@link IOException} to indicate that the stream is closed. - * - * @param b ignored - * @throws IOException always thrown - */ - @Override - public void write(int b) throws IOException { - throw new IOException("write(" + b + ") failed: stream is closed"); - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/output/FileWriterWithEncoding.java b/apacheandroid/src/main/java/org/apache/commons/io/output/FileWriterWithEncoding.java deleted file mode 100644 index 64e1c5e7b..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/output/FileWriterWithEncoding.java +++ /dev/null @@ -1,331 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.output; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.nio.charset.Charset; -import java.nio.charset.CharsetEncoder; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; - -/** - * Writer of files that allows the encoding to be set. - *

- * This class provides a simple alternative to FileWriter - * that allows an encoding to be set. Unfortunately, it cannot subclass - * FileWriter. - *

- * By default, the file will be overwritten, but this may be changed to append. - *

- * The encoding must be specified using either the name of the {@link Charset}, - * the {@link Charset}, or a {@link CharsetEncoder}. If the default encoding - * is required then use the {@link java.io.FileWriter} directly, rather than - * this implementation. - *

- * - * - * @since 1.4 - * @version $Id: FileWriterWithEncoding.java 1304052 2012-03-22 20:55:29Z ggregory $ - */ -public class FileWriterWithEncoding extends Writer { - // Cannot extend ProxyWriter, as requires writer to be - // known when super() is called - - /** The writer to decorate. */ - private final Writer out; - - /** - * Constructs a FileWriterWithEncoding with a file encoding. - * - * @param filename the name of the file to write to, not null - * @param encoding the encoding to use, not null - * @throws NullPointerException if the file name or encoding is null - * @throws IOException in case of an I/O error - */ - public FileWriterWithEncoding(String filename, String encoding) throws IOException { - this(new File(filename), encoding, false); - } - - /** - * Constructs a FileWriterWithEncoding with a file encoding. - * - * @param filename the name of the file to write to, not null - * @param encoding the encoding to use, not null - * @param append true if content should be appended, false to overwrite - * @throws NullPointerException if the file name or encoding is null - * @throws IOException in case of an I/O error - */ - public FileWriterWithEncoding(String filename, String encoding, boolean append) throws IOException { - this(new File(filename), encoding, append); - } - - /** - * Constructs a FileWriterWithEncoding with a file encoding. - * - * @param filename the name of the file to write to, not null - * @param encoding the encoding to use, not null - * @throws NullPointerException if the file name or encoding is null - * @throws IOException in case of an I/O error - */ - public FileWriterWithEncoding(String filename, Charset encoding) throws IOException { - this(new File(filename), encoding, false); - } - - /** - * Constructs a FileWriterWithEncoding with a file encoding. - * - * @param filename the name of the file to write to, not null - * @param encoding the encoding to use, not null - * @param append true if content should be appended, false to overwrite - * @throws NullPointerException if the file name or encoding is null - * @throws IOException in case of an I/O error - */ - public FileWriterWithEncoding(String filename, Charset encoding, boolean append) throws IOException { - this(new File(filename), encoding, append); - } - - /** - * Constructs a FileWriterWithEncoding with a file encoding. - * - * @param filename the name of the file to write to, not null - * @param encoding the encoding to use, not null - * @throws NullPointerException if the file name or encoding is null - * @throws IOException in case of an I/O error - */ - public FileWriterWithEncoding(String filename, CharsetEncoder encoding) throws IOException { - this(new File(filename), encoding, false); - } - - /** - * Constructs a FileWriterWithEncoding with a file encoding. - * - * @param filename the name of the file to write to, not null - * @param encoding the encoding to use, not null - * @param append true if content should be appended, false to overwrite - * @throws NullPointerException if the file name or encoding is null - * @throws IOException in case of an I/O error - */ - public FileWriterWithEncoding(String filename, CharsetEncoder encoding, boolean append) throws IOException { - this(new File(filename), encoding, append); - } - - /** - * Constructs a FileWriterWithEncoding with a file encoding. - * - * @param file the file to write to, not null - * @param encoding the encoding to use, not null - * @throws NullPointerException if the file or encoding is null - * @throws IOException in case of an I/O error - */ - public FileWriterWithEncoding(File file, String encoding) throws IOException { - this(file, encoding, false); - } - - /** - * Constructs a FileWriterWithEncoding with a file encoding. - * - * @param file the file to write to, not null - * @param encoding the encoding to use, not null - * @param append true if content should be appended, false to overwrite - * @throws NullPointerException if the file or encoding is null - * @throws IOException in case of an I/O error - */ - public FileWriterWithEncoding(File file, String encoding, boolean append) throws IOException { - super(); - this.out = initWriter(file, encoding, append); - } - - /** - * Constructs a FileWriterWithEncoding with a file encoding. - * - * @param file the file to write to, not null - * @param encoding the encoding to use, not null - * @throws NullPointerException if the file or encoding is null - * @throws IOException in case of an I/O error - */ - public FileWriterWithEncoding(File file, Charset encoding) throws IOException { - this(file, encoding, false); - } - - /** - * Constructs a FileWriterWithEncoding with a file encoding. - * - * @param file the file to write to, not null - * @param encoding the encoding to use, not null - * @param append true if content should be appended, false to overwrite - * @throws NullPointerException if the file or encoding is null - * @throws IOException in case of an I/O error - */ - public FileWriterWithEncoding(File file, Charset encoding, boolean append) throws IOException { - super(); - this.out = initWriter(file, encoding, append); - } - - /** - * Constructs a FileWriterWithEncoding with a file encoding. - * - * @param file the file to write to, not null - * @param encoding the encoding to use, not null - * @throws NullPointerException if the file or encoding is null - * @throws IOException in case of an I/O error - */ - public FileWriterWithEncoding(File file, CharsetEncoder encoding) throws IOException { - this(file, encoding, false); - } - - /** - * Constructs a FileWriterWithEncoding with a file encoding. - * - * @param file the file to write to, not null - * @param encoding the encoding to use, not null - * @param append true if content should be appended, false to overwrite - * @throws NullPointerException if the file or encoding is null - * @throws IOException in case of an I/O error - */ - public FileWriterWithEncoding(File file, CharsetEncoder encoding, boolean append) throws IOException { - super(); - this.out = initWriter(file, encoding, append); - } - - //----------------------------------------------------------------------- - /** - * Initialise the wrapped file writer. - * Ensure that a cleanup occurs if the writer creation fails. - * - * @param file the file to be accessed - * @param encoding the encoding to use - may be Charset, CharsetEncoder or String - * @param append true to append - * @return the initialised writer - * @throws NullPointerException if the file or encoding is null - * @throws IOException if an error occurs - */ - private static Writer initWriter(File file, Object encoding, boolean append) throws IOException { - if (file == null) { - throw new NullPointerException("File is missing"); - } - if (encoding == null) { - throw new NullPointerException("Encoding is missing"); - } - boolean fileExistedAlready = file.exists(); - OutputStream stream = null; - Writer writer = null; - try { - stream = new FileOutputStream(file, append); - if (encoding instanceof Charset) { - writer = new OutputStreamWriter(stream, (Charset)encoding); - } else if (encoding instanceof CharsetEncoder) { - writer = new OutputStreamWriter(stream, (CharsetEncoder)encoding); - } else { - writer = new OutputStreamWriter(stream, (String)encoding); - } - } catch (IOException ex) { - IOUtils.closeQuietly(writer); - IOUtils.closeQuietly(stream); - if (fileExistedAlready == false) { - FileUtils.deleteQuietly(file); - } - throw ex; - } catch (RuntimeException ex) { - IOUtils.closeQuietly(writer); - IOUtils.closeQuietly(stream); - if (fileExistedAlready == false) { - FileUtils.deleteQuietly(file); - } - throw ex; - } - return writer; - } - - //----------------------------------------------------------------------- - /** - * Write a character. - * @param idx the character to write - * @throws IOException if an I/O error occurs - */ - @Override - public void write(int idx) throws IOException { - out.write(idx); - } - - /** - * Write the characters from an array. - * @param chr the characters to write - * @throws IOException if an I/O error occurs - */ - @Override - public void write(char[] chr) throws IOException { - out.write(chr); - } - - /** - * Write the specified characters from an array. - * @param chr the characters to write - * @param st The start offset - * @param end The number of characters to write - * @throws IOException if an I/O error occurs - */ - @Override - public void write(char[] chr, int st, int end) throws IOException { - out.write(chr, st, end); - } - - /** - * Write the characters from a string. - * @param str the string to write - * @throws IOException if an I/O error occurs - */ - @Override - public void write(String str) throws IOException { - out.write(str); - } - - /** - * Write the specified characters from a string. - * @param str the string to write - * @param st The start offset - * @param end The number of characters to write - * @throws IOException if an I/O error occurs - */ - @Override - public void write(String str, int st, int end) throws IOException { - out.write(str, st, end); - } - - /** - * Flush the stream. - * @throws IOException if an I/O error occurs - */ - @Override - public void flush() throws IOException { - out.flush(); - } - - /** - * Close the stream. - * @throws IOException if an I/O error occurs - */ - @Override - public void close() throws IOException { - out.close(); - } -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/output/NullOutputStream.java b/apacheandroid/src/main/java/org/apache/commons/io/output/NullOutputStream.java deleted file mode 100644 index 55f6d0c2b..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/output/NullOutputStream.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.output; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * This OutputStream writes all data to the famous /dev/null. - *

- * This output stream has no destination (file/socket etc.) and all - * bytes written to it are ignored and lost. - * - * @version $Id: NullOutputStream.java 1302056 2012-03-18 03:03:38Z ggregory $ - */ -public class NullOutputStream extends OutputStream { - - /** - * A singleton. - */ - public static final NullOutputStream NULL_OUTPUT_STREAM = new NullOutputStream(); - - /** - * Does nothing - output to /dev/null. - * @param b The bytes to write - * @param off The start offset - * @param len The number of bytes to write - */ - @Override - public void write(byte[] b, int off, int len) { - //to /dev/null - } - - /** - * Does nothing - output to /dev/null. - * @param b The byte to write - */ - @Override - public void write(int b) { - //to /dev/null - } - - /** - * Does nothing - output to /dev/null. - * @param b The bytes to write - * @throws IOException never - */ - @Override - public void write(byte[] b) throws IOException { - //to /dev/null - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/output/NullWriter.java b/apacheandroid/src/main/java/org/apache/commons/io/output/NullWriter.java deleted file mode 100644 index 7d925ba0e..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/output/NullWriter.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.output; - -import java.io.Writer; - -/** - * This {@link Writer} writes all data to the famous /dev/null. - *

- * This Writer has no destination (file/socket etc.) and all - * characters written to it are ignored and lost. - * - * @version $Id: NullWriter.java 1304052 2012-03-22 20:55:29Z ggregory $ - */ -public class NullWriter extends Writer { - - /** - * A singleton. - */ - public static final NullWriter NULL_WRITER = new NullWriter(); - - /** - * Constructs a new NullWriter. - */ - public NullWriter() { - } - - /** - * Does nothing - output to /dev/null. - * @param c The character to write - * @return this writer - * @since 2.0 - */ - @Override - public Writer append(char c) { - //to /dev/null - return this; - } - - /** - * Does nothing - output to /dev/null. - * @param csq The character sequence to write - * @param start The index of the first character to write - * @param end The index of the first character to write (exclusive) - * @return this writer - * @since 2.0 - */ - @Override - public Writer append(CharSequence csq, int start, int end) { - //to /dev/null - return this; - } - - /** - * Does nothing - output to /dev/null. - * @param csq The character sequence to write - * @return this writer - * @since 2.0 - */ - @Override - public Writer append(CharSequence csq) { - //to /dev/null - return this; - } - - /** - * Does nothing - output to /dev/null. - * @param idx The character to write - */ - @Override - public void write(int idx) { - //to /dev/null - } - - /** - * Does nothing - output to /dev/null. - * @param chr The characters to write - */ - @Override - public void write(char[] chr) { - //to /dev/null - } - - /** - * Does nothing - output to /dev/null. - * @param chr The characters to write - * @param st The start offset - * @param end The number of characters to write - */ - @Override - public void write(char[] chr, int st, int end) { - //to /dev/null - } - - /** - * Does nothing - output to /dev/null. - * @param str The string to write - */ - @Override - public void write(String str) { - //to /dev/null - } - - /** - * Does nothing - output to /dev/null. - * @param str The string to write - * @param st The start offset - * @param end The number of characters to write - */ - @Override - public void write(String str, int st, int end) { - //to /dev/null - } - - /** @see java.io.Writer#flush() */ - @Override - public void flush() { - //to /dev/null - } - - /** @see java.io.Writer#close() */ - @Override - public void close() { - //to /dev/null - } - -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/output/StringBuilderWriter.java b/apacheandroid/src/main/java/org/apache/commons/io/output/StringBuilderWriter.java deleted file mode 100644 index 6943597b0..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/output/StringBuilderWriter.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.output; - -import java.io.Serializable; -import java.io.Writer; - -/** - * {@link Writer} implementation that outputs to a {@link StringBuilder}. - *

- * NOTE: This implementation, as an alternative to - * java.io.StringWriter, provides an un-synchronized - * (i.e. for use in a single thread) implementation for better performance. - * For safe usage with multiple {@link Thread}s then - * java.io.StringWriter should be used. - * - * @version $Id: StringBuilderWriter.java 1304052 2012-03-22 20:55:29Z ggregory $ - * @since 2.0 - */ -public class StringBuilderWriter extends Writer implements Serializable { - - private final StringBuilder builder; - - /** - * Construct a new {@link StringBuilder} instance with default capacity. - */ - public StringBuilderWriter() { - this.builder = new StringBuilder(); - } - - /** - * Construct a new {@link StringBuilder} instance with the specified capacity. - * - * @param capacity The initial capacity of the underlying {@link StringBuilder} - */ - public StringBuilderWriter(int capacity) { - this.builder = new StringBuilder(capacity); - } - - /** - * Construct a new instance with the specified {@link StringBuilder}. - * - * @param builder The String builder - */ - public StringBuilderWriter(StringBuilder builder) { - this.builder = builder != null ? builder : new StringBuilder(); - } - - /** - * Append a single character to this Writer. - * - * @param value The character to append - * @return This writer instance - */ - @Override - public Writer append(char value) { - builder.append(value); - return this; - } - - /** - * Append a character sequence to this Writer. - * - * @param value The character to append - * @return This writer instance - */ - @Override - public Writer append(CharSequence value) { - builder.append(value); - return this; - } - - /** - * Append a portion of a character sequence to the {@link StringBuilder}. - * - * @param value The character to append - * @param start The index of the first character - * @param end The index of the last character + 1 - * @return This writer instance - */ - @Override - public Writer append(CharSequence value, int start, int end) { - builder.append(value, start, end); - return this; - } - - /** - * Closing this writer has no effect. - */ - @Override - public void close() { - } - - /** - * Flushing this writer has no effect. - */ - @Override - public void flush() { - } - - - /** - * Write a String to the {@link StringBuilder}. - * - * @param value The value to write - */ - @Override - public void write(String value) { - if (value != null) { - builder.append(value); - } - } - - /** - * Write a portion of a character array to the {@link StringBuilder}. - * - * @param value The value to write - * @param offset The index of the first character - * @param length The number of characters to write - */ - @Override - public void write(char[] value, int offset, int length) { - if (value != null) { - builder.append(value, offset, length); - } - } - - /** - * Return the underlying builder. - * - * @return The underlying builder - */ - public StringBuilder getBuilder() { - return builder; - } - - /** - * Returns {@link StringBuilder#toString()}. - * - * @return The contents of the String builder. - */ - @Override - public String toString() { - return builder.toString(); - } -} diff --git a/apacheandroid/src/main/java/org/apache/commons/io/output/WriterOutputStream.java b/apacheandroid/src/main/java/org/apache/commons/io/output/WriterOutputStream.java deleted file mode 100644 index 3dcf49e17..000000000 --- a/apacheandroid/src/main/java/org/apache/commons/io/output/WriterOutputStream.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.commons.io.output; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.Writer; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CoderResult; -import java.nio.charset.CodingErrorAction; - -/** - * {@link OutputStream} implementation that transforms a byte stream to a - * character stream using a specified charset encoding and writes the resulting - * stream to a {@link Writer}. The stream is transformed using a - * {@link CharsetDecoder} object, guaranteeing that all charset - * encodings supported by the JRE are handled correctly. - *

- * The output of the {@link CharsetDecoder} is buffered using a fixed size buffer. - * This implies that the data is written to the underlying {@link Writer} in chunks - * that are no larger than the size of this buffer. By default, the buffer is - * flushed only when it overflows or when {@link #flush()} or {@link #close()} - * is called. In general there is therefore no need to wrap the underlying {@link Writer} - * in a {@link java.io.BufferedWriter}. {@link WriterOutputStream} can also - * be instructed to flush the buffer after each write operation. In this case, all - * available data is written immediately to the underlying {@link Writer}, implying that - * the current position of the {@link Writer} is correlated to the current position - * of the {@link WriterOutputStream}. - *

- * {@link WriterOutputStream} implements the inverse transformation of {@link java.io.OutputStreamWriter}; - * in the following example, writing to out2 would have the same result as writing to - * out directly (provided that the byte sequence is legal with respect to the - * charset encoding): - *

- * OutputStream out = ...
- * Charset cs = ...
- * OutputStreamWriter writer = new OutputStreamWriter(out, cs);
- * WriterOutputStream out2 = new WriterOutputStream(writer, cs);
- * {@link WriterOutputStream} implements the same transformation as {@link java.io.InputStreamReader}, - * except that the control flow is reversed: both classes transform a byte stream - * into a character stream, but {@link java.io.InputStreamReader} pulls data from the underlying stream, - * while {@link WriterOutputStream} pushes it to the underlying stream. - *

- * Note that while there are use cases where there is no alternative to using - * this class, very often the need to use this class is an indication of a flaw - * in the design of the code. This class is typically used in situations where an existing - * API only accepts an {@link OutputStream} object, but where the stream is known to represent - * character data that must be decoded for further use. - *

- * Instances of {@link WriterOutputStream} are not thread safe. - * - * @see org.apache.commons.io.input.ReaderInputStream - * - * @since 2.0 - */ -public class WriterOutputStream extends OutputStream { - private static final int DEFAULT_BUFFER_SIZE = 1024; - - private final Writer writer; - private final CharsetDecoder decoder; - private final boolean writeImmediately; - - /** - * ByteBuffer used as input for the decoder. This buffer can be small - * as it is used only to transfer the received data to the - * decoder. - */ - private final ByteBuffer decoderIn = ByteBuffer.allocate(128); - - /** - * CharBuffer used as output for the decoder. It should be - * somewhat larger as we write from this buffer to the - * underlying Writer. - */ - private final CharBuffer decoderOut; - - /** - * Constructs a new {@link WriterOutputStream} with a default output buffer size of - * 1024 characters. The output buffer will only be flushed when it overflows or when - * {@link #flush()} or {@link #close()} is called. - * - * @param writer the target {@link Writer} - * @param decoder the charset decoder - * @since 2.1 - */ - public WriterOutputStream(Writer writer, CharsetDecoder decoder) { - this(writer, decoder, DEFAULT_BUFFER_SIZE, false); - } - - /** - * Constructs a new {@link WriterOutputStream}. - * - * @param writer the target {@link Writer} - * @param decoder the charset decoder - * @param bufferSize the size of the output buffer in number of characters - * @param writeImmediately If true the output buffer will be flushed after each - * write operation, i.e. all available data will be written to the - * underlying {@link Writer} immediately. If false, the - * output buffer will only be flushed when it overflows or when - * {@link #flush()} or {@link #close()} is called. - * @since 2.1 - */ - public WriterOutputStream(Writer writer, CharsetDecoder decoder, int bufferSize, boolean writeImmediately) { - this.writer = writer; - this.decoder = decoder; - this.writeImmediately = writeImmediately; - decoderOut = CharBuffer.allocate(bufferSize); - } - - /** - * Constructs a new {@link WriterOutputStream}. - * - * @param writer the target {@link Writer} - * @param charset the charset encoding - * @param bufferSize the size of the output buffer in number of characters - * @param writeImmediately If true the output buffer will be flushed after each - * write operation, i.e. all available data will be written to the - * underlying {@link Writer} immediately. If false, the - * output buffer will only be flushed when it overflows or when - * {@link #flush()} or {@link #close()} is called. - */ - public WriterOutputStream(Writer writer, Charset charset, int bufferSize, boolean writeImmediately) { - this(writer, - charset.newDecoder() - .onMalformedInput(CodingErrorAction.REPLACE) - .onUnmappableCharacter(CodingErrorAction.REPLACE) - .replaceWith("?"), - bufferSize, - writeImmediately); - } - - /** - * Constructs a new {@link WriterOutputStream} with a default output buffer size of - * 1024 characters. The output buffer will only be flushed when it overflows or when - * {@link #flush()} or {@link #close()} is called. - * - * @param writer the target {@link Writer} - * @param charset the charset encoding - */ - public WriterOutputStream(Writer writer, Charset charset) { - this(writer, charset, DEFAULT_BUFFER_SIZE, false); - } - - /** - * Constructs a new {@link WriterOutputStream}. - * - * @param writer the target {@link Writer} - * @param charsetName the name of the charset encoding - * @param bufferSize the size of the output buffer in number of characters - * @param writeImmediately If true the output buffer will be flushed after each - * write operation, i.e. all available data will be written to the - * underlying {@link Writer} immediately. If false, the - * output buffer will only be flushed when it overflows or when - * {@link #flush()} or {@link #close()} is called. - */ - public WriterOutputStream(Writer writer, String charsetName, int bufferSize, boolean writeImmediately) { - this(writer, Charset.forName(charsetName), bufferSize, writeImmediately); - } - - /** - * Constructs a new {@link WriterOutputStream} with a default output buffer size of - * 1024 characters. The output buffer will only be flushed when it overflows or when - * {@link #flush()} or {@link #close()} is called. - * - * @param writer the target {@link Writer} - * @param charsetName the name of the charset encoding - */ - public WriterOutputStream(Writer writer, String charsetName) { - this(writer, charsetName, DEFAULT_BUFFER_SIZE, false); - } - - /** - * Constructs a new {@link WriterOutputStream} that uses the default character encoding - * and with a default output buffer size of 1024 characters. The output buffer will only - * be flushed when it overflows or when {@link #flush()} or {@link #close()} is called. - * - * @param writer the target {@link Writer} - */ - public WriterOutputStream(Writer writer) { - this(writer, Charset.defaultCharset(), DEFAULT_BUFFER_SIZE, false); - } - - /** - * Write bytes from the specified byte array to the stream. - * - * @param b the byte array containing the bytes to write - * @param off the start offset in the byte array - * @param len the number of bytes to write - * @throws IOException if an I/O error occurs - */ - @Override - public void write(byte[] b, int off, int len) throws IOException { - while (len > 0) { - int c = Math.min(len, decoderIn.remaining()); - decoderIn.put(b, off, c); - processInput(false); - len -= c; - off += c; - } - if (writeImmediately) { - flushOutput(); - } - } - - /** - * Write bytes from the specified byte array to the stream. - * - * @param b the byte array containing the bytes to write - * @throws IOException if an I/O error occurs - */ - @Override - public void write(byte[] b) throws IOException { - write(b, 0, b.length); - } - - /** - * Write a single byte to the stream. - * - * @param b the byte to write - * @throws IOException if an I/O error occurs - */ - @Override - public void write(int b) throws IOException { - write(new byte[] { (byte)b }, 0, 1); - } - - /** - * Flush the stream. Any remaining content accumulated in the output buffer - * will be written to the underlying {@link Writer}. After that - * {@link Writer#flush()} will be called. - * @throws IOException if an I/O error occurs - */ - @Override - public void flush() throws IOException { - flushOutput(); - writer.flush(); - } - - /** - * Close the stream. Any remaining content accumulated in the output buffer - * will be written to the underlying {@link Writer}. After that - * {@link Writer#close()} will be called. - * @throws IOException if an I/O error occurs - */ - @Override - public void close() throws IOException { - processInput(true); - flushOutput(); - writer.close(); - } - - /** - * Decode the contents of the input ByteBuffer into a CharBuffer. - * - * @param endOfInput indicates end of input - * @throws IOException if an I/O error occurs - */ - private void processInput(boolean endOfInput) throws IOException { - // Prepare decoderIn for reading - decoderIn.flip(); - CoderResult coderResult; - while (true) { - coderResult = decoder.decode(decoderIn, decoderOut, endOfInput); - if (coderResult.isOverflow()) { - flushOutput(); - } else if (coderResult.isUnderflow()) { - break; - } else { - // The decoder is configured to replace malformed input and unmappable characters, - // so we should not get here. - throw new IOException("Unexpected coder result"); - } - } - // Discard the bytes that have been read - decoderIn.compact(); - } - - /** - * Flush the output. - * - * @throws IOException if an I/O error occurs - */ - private void flushOutput() throws IOException { - if (decoderOut.position() > 0) { - writer.write(decoderOut.array(), 0, decoderOut.position()); - decoderOut.rewind(); - } - } -}