/* * 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.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; 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.Reader; import java.io.Writer; import java.net.HttpURLConnection; import java.net.ServerSocket; import java.net.Socket; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.Selector; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.function.Consumer; import org.apache.commons.io.function.IOConsumer; import org.apache.commons.io.output.AppendableWriter; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.commons.io.output.NullOutputStream; import org.apache.commons.io.output.StringBuilderWriter; import org.apache.commons.io.output.ThresholdingOutputStream; import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; /** * General IO stream manipulation utilities. *
* This class provides static utility methods for input/output operations. *
* 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 {@code BufferedInputStream} * or {@code BufferedReader}. The default buffer size of 4K has been shown * to be efficient in tests. *
* The various copy methods all delegate the actual copying to one of the following methods: *
* Applications can re-use buffers by using the underlying methods directly. * This may improve performance for applications that need to do a lot of copying. *
* 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.
*/
public class IOUtils {
// NOTE: This class is focused on InputStream, OutputStream, Reader and
// Writer. Each method should take at least one of these as a parameter,
// or return one of them.
/**
* CR char.
*
* @since 2.9.0
*/
public static final int CR = '\r';
/**
* The default buffer size ({@value}) to use in copy methods.
*/
public static final int DEFAULT_BUFFER_SIZE = 8192;
/**
* The system directory separator character.
*/
public static final char DIR_SEPARATOR = File.separatorChar;
/**
* The Unix directory separator character.
*/
public static final char DIR_SEPARATOR_UNIX = '/';
/**
* The Windows directory separator character.
*/
public static final char DIR_SEPARATOR_WINDOWS = '\\';
/**
* A singleton empty byte array.
*
* @since 2.9.0
*/
public static final byte[] EMPTY_BYTE_ARRAY = {};
/**
* Represents the end-of-file (or stream).
* @since 2.5 (made public)
*/
public static final int EOF = -1;
/**
* LF char.
*
* @since 2.9.0
*/
public static final int LF = '\n';
/**
* The system line separator string.
*
* @deprecated Use {@link System#lineSeparator()}.
*/
@Deprecated
public static final String LINE_SEPARATOR = System.lineSeparator();
/**
* The Unix line separator string.
*
* @see StandardLineSeparator#LF
*/
public static final String LINE_SEPARATOR_UNIX = StandardLineSeparator.LF.getString();
/**
* The Windows line separator string.
*
* @see StandardLineSeparator#CRLF
*/
public static final String LINE_SEPARATOR_WINDOWS = StandardLineSeparator.CRLF.getString();
/**
* Internal byte array buffer.
*/
private static final ThreadLocal
* Equivalent to {@link Closeable#close()}, except any exceptions will be ignored. This is typically used in
* finally blocks.
*
* Example code:
*
* Closing all streams:
*
* Also consider using a try-with-resources statement where appropriate.
*
* Equivalent to {@link Closeable#close()}, except any exceptions will be ignored.
*
* This is typically used in finally blocks to ensure that the closeable is closed
* even if an Exception was thrown before the normal close statement was reached.
*
* Example code:
*
* Closing all streams:
*
* Also consider using a try-with-resources statement where appropriate.
*
* Equivalent to {@link InputStream#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
*
* Example code:
*
* Also consider using a try-with-resources statement where appropriate.
*
* Equivalent to {@link OutputStream#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
*
* Example code:
*
* Also consider using a try-with-resources statement where appropriate.
*
* Equivalent to {@link Reader#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
*
* Example code:
*
* Also consider using a try-with-resources statement where appropriate.
*
* Equivalent to {@link Selector#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
*
* Example code:
*
* Also consider using a try-with-resources statement where appropriate.
*
* Equivalent to {@link ServerSocket#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
*
* Example code:
*
* Also consider using a try-with-resources statement where appropriate.
*
* Equivalent to {@link Socket#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
*
* Example code:
*
* Also consider using a try-with-resources statement where appropriate.
*
* Equivalent to {@link Writer#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
*
* Example code:
*
* Also consider using a try-with-resources statement where appropriate.
*
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
*
* This method buffers the input internally using
* {@code BufferedInputStream} if they are not already buffered.
*
* This method buffers the input internally using {@code BufferedReader} if they are not already buffered.
*
* This method buffers the input internally using
* {@code BufferedReader} if they are not already buffered.
*
* @param reader1 the first reader
* @param reader2 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
*/
@SuppressWarnings("resource")
public static boolean contentEqualsIgnoreEOL(final Reader reader1, final Reader reader2)
throws IOException {
if (reader1 == reader2) {
return true;
}
if (reader1 == null ^ reader2 == null) {
return false;
}
final BufferedReader br1 = toBufferedReader(reader1);
final BufferedReader br2 = toBufferedReader(reader2);
String line1 = br1.readLine();
String line2 = br2.readLine();
while (line1 != null && line1.equals(line2)) {
line1 = br1.readLine();
line2 = br2.readLine();
}
return Objects.equals(line1, line2);
}
/**
* Copies bytes from an {@code InputStream} to an {@code OutputStream}.
*
* This method buffers the input internally, so there is no need to use a {@code BufferedInputStream}.
*
* Large streams (over 2GB) will return a bytes copied value of {@code -1} after the copy has completed since
* the correct number of bytes cannot be returned as an int. For large streams use the
* {@code copyLarge(InputStream, OutputStream)} method.
*
* This method buffers the input internally, so there is no need to use a {@code BufferedInputStream}.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedInputStream}.
*
* This method uses {@link InputStreamReader}.
*
* @param input the {@code InputStream} to read from
* @param writer the {@code Writer} to write to
* @throws NullPointerException if the input or output is null
* @throws IOException if an I/O error occurs
* @since 1.1
* @deprecated 2.5 use {@link #copy(InputStream, Writer, Charset)} instead
*/
@Deprecated
public static void copy(final InputStream input, final Writer writer)
throws IOException {
copy(input, writer, Charset.defaultCharset());
}
/**
* Copies bytes from an {@code InputStream} to chars on a
* {@code Writer} using the specified character encoding.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedInputStream}.
*
* This method uses {@link InputStreamReader}.
*
* @param input the {@code InputStream} to read from
* @param writer the {@code Writer} to write to
* @param inputCharset the charset to use for the input stream, null means platform default
* @throws NullPointerException if the input or output is null
* @throws IOException if an I/O error occurs
* @since 2.3
*/
public static void copy(final InputStream input, final Writer writer, final Charset inputCharset)
throws IOException {
final InputStreamReader reader = new InputStreamReader(input, Charsets.toCharset(inputCharset));
copy(reader, writer);
}
/**
* Copies bytes from an {@code InputStream} to chars on a
* {@code Writer} using the specified character encoding.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedInputStream}.
*
* Character encoding names can be found at
* IANA.
*
* This method uses {@link InputStreamReader}.
*
* @param input the {@code InputStream} to read from
* @param writer the {@code Writer} to write to
* @param inputCharsetName the name of the requested charset for the InputStream, null means platform default
* @throws NullPointerException if the input or output is null
* @throws IOException if an I/O error occurs
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the
* encoding is not supported.
* @since 1.1
*/
public static void copy(final InputStream input, final Writer writer, final String inputCharsetName)
throws IOException {
copy(input, writer, Charsets.toCharset(inputCharsetName));
}
/**
* Copies chars from a {@code Reader} to a {@code Appendable}.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedReader}.
*
* Large streams (over 2GB) will return a chars copied value of
* {@code -1} after the copy has completed since the correct
* number of chars cannot be returned as an int. For large streams
* use the {@code copyLarge(Reader, Writer)} method.
*
* @param reader the {@code Reader} to read from
* @param output the {@code Appendable} 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 2.7
*/
public static long copy(final Reader reader, final Appendable output) throws IOException {
return copy(reader, output, CharBuffer.allocate(DEFAULT_BUFFER_SIZE));
}
/**
* Copies chars from a {@code Reader} to an {@code Appendable}.
*
* This method uses the provided buffer, so there is no need to use a
* {@code BufferedReader}.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedReader}.
*
* Due to the implementation of OutputStreamWriter, this method performs a
* flush.
*
* This method uses {@link OutputStreamWriter}.
*
* @param reader the {@code Reader} to read from
* @param output the {@code OutputStream} to write to
* @throws NullPointerException if the input or output is null
* @throws IOException if an I/O error occurs
* @since 1.1
* @deprecated 2.5 use {@link #copy(Reader, OutputStream, Charset)} instead
*/
@Deprecated
public static void copy(final Reader reader, final OutputStream output)
throws IOException {
copy(reader, output, Charset.defaultCharset());
}
/**
* Copies chars from a {@code Reader} to bytes on an
* {@code OutputStream} using the specified character encoding, and
* calling flush.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedReader}.
*
* Due to the implementation of OutputStreamWriter, this method performs a
* flush.
*
* This method uses {@link OutputStreamWriter}.
*
* This method buffers the input internally, so there is no need to use a
* {@code 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 reader the {@code Reader} to read from
* @param output the {@code OutputStream} to write to
* @param outputCharsetName the name of the requested charset for the OutputStream, null means platform default
* @throws NullPointerException if the input or output is null
* @throws IOException if an I/O error occurs
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the
* encoding is not supported.
* @since 1.1
*/
public static void copy(final Reader reader, final OutputStream output, final String outputCharsetName)
throws IOException {
copy(reader, output, Charsets.toCharset(outputCharsetName));
}
/**
* Copies chars from a {@code Reader} to a {@code Writer}.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedReader}.
*
* Large streams (over 2GB) will return a chars copied value of
* {@code -1} after the copy has completed since the correct
* number of chars cannot be returned as an int. For large streams
* use the {@code copyLarge(Reader, Writer)} method.
*
* @param reader the {@code Reader} to read.
* @param writer the {@code Writer} to write.
* @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(final Reader reader, final Writer writer) throws IOException {
final long count = copyLarge(reader, writer);
if (count > Integer.MAX_VALUE) {
return EOF;
}
return (int) count;
}
/**
* Copies bytes from a {@code URL} to an {@code OutputStream}.
*
* This method buffers the input internally, so there is no need to use a {@code BufferedInputStream}.
*
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
*
* This method buffers the input internally, so there is no need to use a {@code BufferedInputStream}.
*
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedInputStream}.
*
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
*
* This method uses the provided buffer, so there is no need to use a
* {@code BufferedInputStream}.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedInputStream}.
*
* Note that the implementation uses {@link #skip(InputStream, long)}.
* This means that the method may be considerably less efficient than using the actual skip implementation,
* this is done to guarantee that the correct number of characters are skipped.
*
* This method uses the provided buffer, so there is no need to use a
* {@code BufferedInputStream}.
*
* Note that the implementation uses {@link #skip(InputStream, long)}.
* This means that the method may be considerably less efficient than using the actual skip implementation,
* this is done to guarantee that the correct number of characters are skipped.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedReader}.
*
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
*
* @param reader the {@code Reader} to source.
* @param writer the {@code Writer} to target.
* @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(final Reader reader, final Writer writer) throws IOException {
return copyLarge(reader, writer, getCharArray());
}
/**
* Copies chars from a large (over 2GB) {@code Reader} to a {@code Writer}.
*
* This method uses the provided buffer, so there is no need to use a
* {@code BufferedReader}.
*
*
* @param reader the {@code Reader} to source.
* @param writer the {@code Writer} to target.
* @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(final Reader reader, final Writer writer, final char[] buffer) throws IOException {
long count = 0;
int n;
while (EOF != (n = reader.read(buffer))) {
writer.write(buffer, 0, n);
count += n;
}
return count;
}
/**
* Copies some or all chars from a large (over 2GB) {@code InputStream} to an
* {@code OutputStream}, optionally skipping input chars.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedReader}.
*
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
*
* @param reader the {@code Reader} to read from
* @param writer the {@code 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(final Reader reader, final Writer writer, final long inputOffset, final long length)
throws IOException {
return copyLarge(reader, writer, inputOffset, length, getCharArray());
}
/**
* Copies some or all chars from a large (over 2GB) {@code InputStream} to an
* {@code OutputStream}, optionally skipping input chars.
*
* This method uses the provided buffer, so there is no need to use a
* {@code BufferedReader}.
*
*
* @param reader the {@code Reader} to read from
* @param writer the {@code 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(final Reader reader, final Writer writer, final long inputOffset, final long length,
final char[] buffer)
throws IOException {
if (inputOffset > 0) {
skipFully(reader, 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 = reader.read(buffer, 0, bytesToRead))) {
writer.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;
}
/**
* Gets the thread local byte array.
*
* @return the thread local byte array.
*/
static byte[] getByteArray() {
return SKIP_BYTE_BUFFER.get();
}
/**
* Gets the thread local char array.
*
* @return the thread local char array.
*/
static char[] getCharArray() {
return SKIP_CHAR_BUFFER.get();
}
/**
* Returns the length of the given array in a null-safe manner.
*
* @param array an array or null
* @return the array length -- or 0 if the given array is null.
* @since 2.7
*/
public static int length(final byte[] array) {
return array == null ? 0 : array.length;
}
/**
* Returns the length of the given array in a null-safe manner.
*
* @param array an array or null
* @return the array length -- or 0 if the given array is null.
* @since 2.7
*/
public static int length(final char[] array) {
return array == null ? 0 : array.length;
}
/**
* Returns the length of the given CharSequence in a null-safe manner.
*
* @param csq a CharSequence or null
* @return the CharSequence length -- or 0 if the given CharSequence is null.
* @since 2.7
*/
public static int length(final CharSequence csq) {
return csq == null ? 0 : csq.length();
}
/**
* Returns the length of the given array in a null-safe manner.
*
* @param array an array or null
* @return the array length -- or 0 if the given array is null.
* @since 2.7
*/
public static int length(final Object[] array) {
return array == null ? 0 : array.length;
}
/**
* Returns an Iterator for the lines in an {@code InputStream}, using
* the character encoding specified (or default encoding if null).
*
* {@code LineIterator} holds a reference to the open
* {@code 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:
*
* {@code LineIterator} holds a reference to the open
* {@code 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:
*
* {@code LineIterator} holds a reference to the open
* {@code 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:
*
* 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 ReadableByteChannel}.
*
* @param input the byte channel to read
* @param buffer byte buffer destination
* @return the actual length read; may be less than requested if EOF was reached
* @throws IOException if a read error occurs
* @since 2.5
*/
public static int read(final ReadableByteChannel input, final ByteBuffer buffer) throws IOException {
final int length = buffer.remaining();
while (buffer.remaining() > 0) {
final int count = input.read(buffer);
if (EOF == count) { // EOF
break;
}
}
return length - buffer.remaining();
}
/**
* Reads 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 reader 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(final Reader reader, final char[] buffer) throws IOException {
return read(reader, buffer, 0, buffer.length);
}
/**
* Reads 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 reader where to read input from
* @param buffer destination
* @param offset initial 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(final Reader reader, final char[] buffer, final int offset, final int length)
throws IOException {
if (length < 0) {
throw new IllegalArgumentException("Length must not be negative: " + length);
}
int remaining = length;
while (remaining > 0) {
final int location = length - remaining;
final int count = reader.read(buffer, offset + location, remaining);
if (EOF == count) { // EOF
break;
}
remaining -= count;
}
return length - remaining;
}
/**
* Reads 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(final InputStream input, final byte[] buffer) throws IOException {
readFully(input, buffer, 0, buffer.length);
}
/**
* Reads 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 initial 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(final InputStream input, final byte[] buffer, final int offset, final int length)
throws IOException {
final int actual = read(input, buffer, offset, length);
if (actual != length) {
throw new EOFException("Length to read: " + length + " actual: " + actual);
}
}
/**
* Reads 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 length length to read, must be >= 0
* @return the bytes read from input
* @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.5
*/
public static byte[] readFully(final InputStream input, final int length) throws IOException {
final byte[] buffer = IOUtils.byteArray(length);
readFully(input, buffer, 0, buffer.length);
return buffer;
}
/**
* Reads the requested number of bytes or fail if there are not enough left.
*
* This allows for the possibility that {@link ReadableByteChannel#read(ByteBuffer)} may
* not read as many bytes as requested (most likely because of reaching EOF).
*
* @param input the byte channel to read
* @param buffer byte buffer destination
* @throws IOException if there is a problem reading the file
* @throws EOFException if the number of bytes read was incorrect
* @since 2.5
*/
public static void readFully(final ReadableByteChannel input, final ByteBuffer buffer) throws IOException {
final int expected = buffer.remaining();
final int actual = read(input, buffer);
if (actual != expected) {
throw new EOFException("Length to read: " + expected + " actual: " + actual);
}
}
/**
* Reads 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 reader 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(final Reader reader, final char[] buffer) throws IOException {
readFully(reader, buffer, 0, buffer.length);
}
/**
* Reads 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 reader where to read input from
* @param buffer destination
* @param offset initial 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(final Reader reader, final char[] buffer, final int offset, final int length)
throws IOException {
final int actual = read(reader, buffer, offset, length);
if (actual != length) {
throw new EOFException("Length to read: " + length + " actual: " + actual);
}
}
/**
* Gets the contents of an {@code 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
* {@code BufferedInputStream}.
*
* @param input the {@code 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
* @deprecated 2.5 use {@link #readLines(InputStream, Charset)} instead
*/
@Deprecated
public static List
* This method buffers the input internally, so there is no need to use a
* {@code BufferedInputStream}.
*
* @param input the {@code InputStream} to read from, not null
* @param charset the charset 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 2.3
*/
public static List
* Character encoding names can be found at
* IANA.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedInputStream}.
*
* @param input the {@code InputStream} to read from, not null
* @param charsetName the name of the requested charset, 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
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the
* encoding is not supported.
* @since 1.1
*/
public static List
* This method buffers the input internally, so there is no need to use a
* {@code BufferedReader}.
*
* @param reader the {@code 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
*/
@SuppressWarnings("resource") // reader wraps input and is the responsibility of the caller.
public static List
* It is expected the given {@code name} to be absolute. The
* behavior is not well-defined otherwise.
*
* It is expected the given {@code name} to be absolute. The
* behavior is not well-defined otherwise.
*
* It is expected the given {@code name} to be absolute. The
* behavior is not well-defined otherwise.
*
* It is expected the given {@code name} to be absolute. The
* behavior is not well-defined otherwise.
*
* It is expected the given {@code name} to be absolute. The
* behavior is not well-defined otherwise.
*
* It is expected the given {@code name} to be absolute. The
* behavior is not well-defined otherwise.
*
* Note that the implementation uses {@link InputStream#read(byte[], int, int)} rather
* than delegating to {@link InputStream#skip(long)}.
* This means that the method may be considerably less efficient than using the actual skip implementation,
* this is done to guarantee that the correct number of bytes are skipped.
*
* Note that the implementation uses {@link Reader#read(char[], int, int)} rather
* than delegating to {@link Reader#skip(long)}.
* This means that the method may be considerably less efficient than using the actual skip implementation,
* this is done to guarantee that the correct number of characters are skipped.
*
* This allows for the possibility that {@link InputStream#skip(long)} may
* not skip as many bytes as requested (most likely because of reaching EOF).
*
* Note that the implementation uses {@link #skip(InputStream, long)}.
* This means that the method may be considerably less efficient than using the actual skip implementation,
* this is done to guarantee that the correct number of characters are skipped.
*
* This allows for the possibility that {@link Reader#skip(long)} may
* not skip as many characters as requested (most likely because of reaching EOF).
*
* Note that the implementation uses {@link #skip(Reader, long)}.
* This means that the method may be considerably less efficient than using the actual skip implementation,
* this is done to guarantee that the correct number of characters are skipped.
*
* This method is useful where,
*
* This method is useful where,
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedInputStream}.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedReader}.
*
* @param reader the {@code Reader} to read from
* @return the requested byte array
* @throws NullPointerException if the input is null
* @throws IOException if an I/O error occurs
* @deprecated 2.5 use {@link #toByteArray(Reader, Charset)} instead
*/
@Deprecated
public static byte[] toByteArray(final Reader reader) throws IOException {
return toByteArray(reader, Charset.defaultCharset());
}
/**
* Gets the contents of a {@code Reader} as a {@code byte[]}
* using the specified character encoding.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedReader}.
*
* @param reader the {@code Reader} to read from
* @param charset the charset 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 2.3
*/
public static byte[] toByteArray(final Reader reader, final Charset charset) throws IOException {
try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) {
copy(reader, output, charset);
return output.toByteArray();
}
}
/**
* Gets the contents of a {@code Reader} as a {@code 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
* {@code BufferedReader}.
*
* @param reader the {@code Reader} to read from
* @param charsetName the name of the requested charset, null means platform default
* @return the requested byte array
* @throws NullPointerException if the input is null
* @throws IOException if an I/O error occurs
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the
* encoding is not supported.
* @since 1.1
*/
public static byte[] toByteArray(final Reader reader, final String charsetName) throws IOException {
return toByteArray(reader, Charsets.toCharset(charsetName));
}
/**
* Gets the contents of a {@code String} as a {@code byte[]}
* using the default character encoding of the platform.
*
* This is the same as {@link String#getBytes()}.
*
* @param input the {@code String} to convert
* @return the requested byte array
* @throws NullPointerException if the input is null
* @deprecated 2.5 Use {@link String#getBytes()} instead
*/
@Deprecated
public static byte[] toByteArray(final String input) {
// make explicit the use of the default charset
return input.getBytes(Charset.defaultCharset());
}
/**
* Gets the contents of a {@code URI} as a {@code byte[]}.
*
* @param uri the {@code URI} to read
* @return the requested byte array
* @throws NullPointerException if the uri is null
* @throws IOException if an I/O exception occurs
* @since 2.4
*/
public static byte[] toByteArray(final URI uri) throws IOException {
return IOUtils.toByteArray(uri.toURL());
}
/**
* Gets the contents of a {@code URL} as a {@code byte[]}.
*
* @param url the {@code URL} to read
* @return the requested byte array
* @throws NullPointerException if the input is null
* @throws IOException if an I/O exception occurs
* @since 2.4
*/
public static byte[] toByteArray(final URL url) throws IOException {
final URLConnection conn = url.openConnection();
try {
return IOUtils.toByteArray(conn);
} finally {
close(conn);
}
}
/**
* Gets the contents of a {@code URLConnection} as a {@code byte[]}.
*
* @param urlConn the {@code URLConnection} to read.
* @return the requested byte array.
* @throws NullPointerException if the urlConn is null.
* @throws IOException if an I/O exception occurs.
* @since 2.4
*/
public static byte[] toByteArray(final URLConnection urlConn) throws IOException {
try (InputStream inputStream = urlConn.getInputStream()) {
return IOUtils.toByteArray(inputStream);
}
}
/**
* Gets the contents of an {@code 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
* {@code BufferedInputStream}.
*
* @param inputStream the {@code 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
* @deprecated 2.5 use {@link #toCharArray(InputStream, Charset)} instead
*/
@Deprecated
public static char[] toCharArray(final InputStream inputStream) throws IOException {
return toCharArray(inputStream, Charset.defaultCharset());
}
/**
* Gets the contents of an {@code InputStream} as a character array
* using the specified character encoding.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedInputStream}.
*
* @param inputStream the {@code InputStream} to read from
* @param charset the charset 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 2.3
*/
public static char[] toCharArray(final InputStream inputStream, final Charset charset)
throws IOException {
final CharArrayWriter writer = new CharArrayWriter();
copy(inputStream, writer, charset);
return writer.toCharArray();
}
/**
* Gets the contents of an {@code 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
* {@code BufferedInputStream}.
*
* @param inputStream the {@code InputStream} to read from
* @param charsetName the name of the requested charset, null means platform default
* @return the requested character array
* @throws NullPointerException if the input is null
* @throws IOException if an I/O error occurs
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the
* encoding is not supported.
* @since 1.1
*/
public static char[] toCharArray(final InputStream inputStream, final String charsetName) throws IOException {
return toCharArray(inputStream, Charsets.toCharset(charsetName));
}
/**
* Gets the contents of a {@code Reader} as a character array.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedReader}.
*
* @param reader the {@code 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(final Reader reader) throws IOException {
final CharArrayWriter sw = new CharArrayWriter();
copy(reader, sw);
return sw.toCharArray();
}
/**
* Converts 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
* @deprecated 2.5 use {@link #toInputStream(CharSequence, Charset)} instead
*/
@Deprecated
public static InputStream toInputStream(final CharSequence input) {
return toInputStream(input, Charset.defaultCharset());
}
/**
* Converts the specified CharSequence to an input stream, encoded as bytes
* using the specified character encoding.
*
* @param input the CharSequence to convert
* @param charset the charset to use, null means platform default
* @return an input stream
* @since 2.3
*/
public static InputStream toInputStream(final CharSequence input, final Charset charset) {
return toInputStream(input.toString(), charset);
}
/**
* Converts 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 charsetName the name of the requested charset, null means platform default
* @return an input stream
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the
* encoding is not supported.
* @since 2.0
*/
public static InputStream toInputStream(final CharSequence input, final String charsetName) {
return toInputStream(input, Charsets.toCharset(charsetName));
}
/**
* Converts 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
* @deprecated 2.5 use {@link #toInputStream(String, Charset)} instead
*/
@Deprecated
public static InputStream toInputStream(final String input) {
return toInputStream(input, Charset.defaultCharset());
}
/**
* Converts the specified string to an input stream, encoded as bytes
* using the specified character encoding.
*
* @param input the string to convert
* @param charset the charset to use, null means platform default
* @return an input stream
* @since 2.3
*/
public static InputStream toInputStream(final String input, final Charset charset) {
return new ByteArrayInputStream(input.getBytes(Charsets.toCharset(charset)));
}
/**
* Converts 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 charsetName the name of the requested charset, null means platform default
* @return an input stream
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the
* encoding is not supported.
* @since 1.1
*/
public static InputStream toInputStream(final String input, final String charsetName) {
final byte[] bytes = input.getBytes(Charsets.toCharset(charsetName));
return new ByteArrayInputStream(bytes);
}
/**
* Gets the contents of a {@code 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
* @deprecated 2.5 Use {@link String#String(byte[])} instead
*/
@Deprecated
public static String toString(final byte[] input) {
// make explicit the use of the default charset
return new String(input, Charset.defaultCharset());
}
/**
* Gets the contents of a {@code 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 charsetName the name of the requested charset, null means platform default
* @return the requested String
* @throws NullPointerException if the input is null
*/
public static String toString(final byte[] input, final String charsetName) {
return new String(input, Charsets.toCharset(charsetName));
}
/**
* Gets the contents of an {@code 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
* {@code BufferedInputStream}.
*
* @param input the {@code InputStream} to read from
* @return the requested String
* @throws NullPointerException if the input is null
* @throws IOException if an I/O error occurs
* @deprecated 2.5 use {@link #toString(InputStream, Charset)} instead
*/
@Deprecated
public static String toString(final InputStream input) throws IOException {
return toString(input, Charset.defaultCharset());
}
/**
* Gets the contents of an {@code InputStream} as a String
* using the specified character encoding.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedInputStream}.
*
* Character encoding names can be found at
* IANA.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedInputStream}.
*
* @param input the {@code InputStream} to read from
* @param charsetName the name of the requested charset, null means platform default
* @return the requested String
* @throws NullPointerException if the input is null
* @throws IOException if an I/O error occurs
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the
* encoding is not supported.
*/
public static String toString(final InputStream input, final String charsetName)
throws IOException {
return toString(input, Charsets.toCharset(charsetName));
}
/**
* Gets the contents of a {@code Reader} as a String.
*
* This method buffers the input internally, so there is no need to use a
* {@code BufferedReader}.
*
* @param reader the {@code 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(final Reader reader) throws IOException {
try (final StringBuilderWriter sw = new StringBuilderWriter()) {
copy(reader, 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
* @deprecated 2.5 use {@link #toString(URI, Charset)} instead
*/
@Deprecated
public static String toString(final URI uri) throws IOException {
return toString(uri, Charset.defaultCharset());
}
/**
* 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.3.
*/
public static String toString(final URI uri, final Charset encoding) throws IOException {
return toString(uri.toURL(), Charsets.toCharset(encoding));
}
/**
* Gets the contents at the given URI.
*
* @param uri The URI source.
* @param charsetName The encoding name for the URL contents.
* @return The contents of the URL as a String.
* @throws IOException if an I/O exception occurs.
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the
* encoding is not supported.
* @since 2.1
*/
public static String toString(final URI uri, final String charsetName) throws IOException {
return toString(uri, Charsets.toCharset(charsetName));
}
/**
* 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
* @deprecated 2.5 use {@link #toString(URL, Charset)} instead
*/
@Deprecated
public static String toString(final URL url) throws IOException {
return toString(url, Charset.defaultCharset());
}
/**
* 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.3
*/
public static String toString(final URL url, final Charset encoding) throws IOException {
try (InputStream inputStream = url.openStream()) {
return toString(inputStream, encoding);
}
}
/**
* Gets the contents at the given URL.
*
* @param url The URL source.
* @param charsetName The encoding name for the URL contents.
* @return The contents of the URL as a String.
* @throws IOException if an I/O exception occurs.
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the
* encoding is not supported.
* @since 2.1
*/
public static String toString(final URL url, final String charsetName) throws IOException {
return toString(url, Charsets.toCharset(charsetName));
}
/**
* Writes bytes from a {@code byte[]} to an {@code OutputStream}.
*
* @param data the byte array to write, do not modify during output,
* null ignored
* @param output the {@code 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(final byte[] data, final OutputStream output)
throws IOException {
if (data != null) {
output.write(data);
}
}
/**
* Writes bytes from a {@code byte[]} to chars on a {@code 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 writer the {@code Writer} to write to
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @since 1.1
* @deprecated 2.5 use {@link #write(byte[], Writer, Charset)} instead
*/
@Deprecated
public static void write(final byte[] data, final Writer writer) throws IOException {
write(data, writer, Charset.defaultCharset());
}
/**
* Writes bytes from a {@code byte[]} to chars on a {@code Writer}
* using the specified character encoding.
*
* This method uses {@link String#String(byte[], String)}.
*
* @param data the byte array to write, do not modify during output,
* null ignored
* @param writer the {@code Writer} to write to
* @param charset the charset to use, null means platform default
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @since 2.3
*/
public static void write(final byte[] data, final Writer writer, final Charset charset) throws IOException {
if (data != null) {
writer.write(new String(data, Charsets.toCharset(charset)));
}
}
/**
* Writes bytes from a {@code byte[]} to chars on a {@code 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 writer the {@code Writer} to write to
* @param charsetName the name of the requested charset, null means platform default
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the
* encoding is not supported.
* @since 1.1
*/
public static void write(final byte[] data, final Writer writer, final String charsetName) throws IOException {
write(data, writer, Charsets.toCharset(charsetName));
}
/**
* Writes chars from a {@code char[]} to bytes on an
* {@code 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 {@code OutputStream} to write to
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @since 1.1
* @deprecated 2.5 use {@link #write(char[], OutputStream, Charset)} instead
*/
@Deprecated
public static void write(final char[] data, final OutputStream output)
throws IOException {
write(data, output, Charset.defaultCharset());
}
/**
* Writes chars from a {@code char[]} to bytes on an
* {@code OutputStream} using the specified character encoding.
*
* 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 {@code OutputStream} to write to
* @param charset the charset to use, null means platform default
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @since 2.3
*/
public static void write(final char[] data, final OutputStream output, final Charset charset) throws IOException {
if (data != null) {
output.write(new String(data).getBytes(Charsets.toCharset(charset)));
}
}
/**
* Writes chars from a {@code char[]} to bytes on an
* {@code 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 {@code OutputStream} to write to
* @param charsetName the name of the requested charset, null means platform default
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the encoding is not supported.
* @since 1.1
*/
public static void write(final char[] data, final OutputStream output, final String charsetName)
throws IOException {
write(data, output, Charsets.toCharset(charsetName));
}
/**
* Writes chars from a {@code char[]} to a {@code Writer}
*
* @param data the char array to write, do not modify during output,
* null ignored
* @param writer the {@code 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(final char[] data, final Writer writer) throws IOException {
if (data != null) {
writer.write(data);
}
}
/**
* Writes chars from a {@code CharSequence} to bytes on an
* {@code OutputStream} using the default character encoding of the
* platform.
*
* This method uses {@link String#getBytes()}.
*
* @param data the {@code CharSequence} to write, null ignored
* @param output the {@code OutputStream} to write to
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @since 2.0
* @deprecated 2.5 use {@link #write(CharSequence, OutputStream, Charset)} instead
*/
@Deprecated
public static void write(final CharSequence data, final OutputStream output)
throws IOException {
write(data, output, Charset.defaultCharset());
}
/**
* Writes chars from a {@code CharSequence} to bytes on an
* {@code OutputStream} using the specified character encoding.
*
* This method uses {@link String#getBytes(String)}.
*
* @param data the {@code CharSequence} to write, null ignored
* @param output the {@code OutputStream} to write to
* @param charset the charset to use, null means platform default
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @since 2.3
*/
public static void write(final CharSequence data, final OutputStream output, final Charset charset)
throws IOException {
if (data != null) {
write(data.toString(), output, charset);
}
}
/**
* Writes chars from a {@code CharSequence} to bytes on an
* {@code OutputStream} using the specified character encoding.
*
* Character encoding names can be found at
* IANA.
*
* This method uses {@link String#getBytes(String)}.
*
* @param data the {@code CharSequence} to write, null ignored
* @param output the {@code OutputStream} to write to
* @param charsetName the name of the requested charset, null means platform default
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the encoding is not supported.
* @since 2.0
*/
public static void write(final CharSequence data, final OutputStream output, final String charsetName)
throws IOException {
write(data, output, Charsets.toCharset(charsetName));
}
/**
* Writes chars from a {@code CharSequence} to a {@code Writer}.
*
* @param data the {@code CharSequence} to write, null ignored
* @param writer the {@code 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(final CharSequence data, final Writer writer) throws IOException {
if (data != null) {
write(data.toString(), writer);
}
}
/**
* Writes chars from a {@code String} to bytes on an
* {@code OutputStream} using the default character encoding of the
* platform.
*
* This method uses {@link String#getBytes()}.
*
* @param data the {@code String} to write, null ignored
* @param output the {@code OutputStream} to write to
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @since 1.1
* @deprecated 2.5 use {@link #write(String, OutputStream, Charset)} instead
*/
@Deprecated
public static void write(final String data, final OutputStream output)
throws IOException {
write(data, output, Charset.defaultCharset());
}
/**
* Writes chars from a {@code String} to bytes on an
* {@code OutputStream} using the specified character encoding.
*
* This method uses {@link String#getBytes(String)}.
*
* @param data the {@code String} to write, null ignored
* @param output the {@code OutputStream} to write to
* @param charset the charset to use, null means platform default
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @since 2.3
*/
public static void write(final String data, final OutputStream output, final Charset charset) throws IOException {
if (data != null) {
output.write(data.getBytes(Charsets.toCharset(charset)));
}
}
/**
* Writes chars from a {@code String} to bytes on an
* {@code OutputStream} using the specified character encoding.
*
* Character encoding names can be found at
* IANA.
*
* This method uses {@link String#getBytes(String)}.
*
* @param data the {@code String} to write, null ignored
* @param output the {@code OutputStream} to write to
* @param charsetName the name of the requested charset, null means platform default
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the encoding is not supported.
* @since 1.1
*/
public static void write(final String data, final OutputStream output, final String charsetName)
throws IOException {
write(data, output, Charsets.toCharset(charsetName));
}
/**
* Writes chars from a {@code String} to a {@code Writer}.
*
* @param data the {@code String} to write, null ignored
* @param writer the {@code 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(final String data, final Writer writer) throws IOException {
if (data != null) {
writer.write(data);
}
}
/**
* Writes chars from a {@code StringBuffer} to bytes on an
* {@code OutputStream} using the default character encoding of the
* platform.
*
* This method uses {@link String#getBytes()}.
*
* @param data the {@code StringBuffer} to write, null ignored
* @param output the {@code 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(final StringBuffer data, final OutputStream output) //NOSONAR
throws IOException {
write(data, output, (String) null);
}
/**
* Writes chars from a {@code StringBuffer} to bytes on an
* {@code OutputStream} using the specified character encoding.
*
* Character encoding names can be found at
* IANA.
*
* This method uses {@link String#getBytes(String)}.
*
* @param data the {@code StringBuffer} to write, null ignored
* @param output the {@code OutputStream} to write to
* @param charsetName the name of the requested charset, null means platform default
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the encoding is not supported.
* @since 1.1
* @deprecated replaced by write(CharSequence, OutputStream, String)
*/
@Deprecated
public static void write(final StringBuffer data, final OutputStream output, final String charsetName) //NOSONAR
throws IOException {
if (data != null) {
output.write(data.toString().getBytes(Charsets.toCharset(charsetName)));
}
}
/**
* Writes chars from a {@code StringBuffer} to a {@code Writer}.
*
* @param data the {@code StringBuffer} to write, null ignored
* @param writer the {@code 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(final StringBuffer data, final Writer writer) //NOSONAR
throws IOException {
if (data != null) {
writer.write(data.toString());
}
}
/**
* Writes bytes from a {@code byte[]} to an {@code OutputStream} using chunked writes.
* This is intended for writing very large byte arrays which might otherwise cause excessive
* memory usage if the native code has to allocate a copy.
*
* @param data the byte array to write, do not modify during output,
* null ignored
* @param output the {@code OutputStream} to write to
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @since 2.5
*/
public static void writeChunked(final byte[] data, final OutputStream output)
throws IOException {
if (data != null) {
int bytes = data.length;
int offset = 0;
while (bytes > 0) {
final int chunk = Math.min(bytes, DEFAULT_BUFFER_SIZE);
output.write(data, offset, chunk);
bytes -= chunk;
offset += chunk;
}
}
}
/**
* Writes chars from a {@code char[]} to a {@code Writer} using chunked writes.
* This is intended for writing very large byte arrays which might otherwise cause excessive
* memory usage if the native code has to allocate a copy.
*
* @param data the char array to write, do not modify during output,
* null ignored
* @param writer the {@code Writer} to write to
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @since 2.5
*/
public static void writeChunked(final char[] data, final Writer writer) throws IOException {
if (data != null) {
int bytes = data.length;
int offset = 0;
while (bytes > 0) {
final int chunk = Math.min(bytes, DEFAULT_BUFFER_SIZE);
writer.write(data, offset, chunk);
bytes -= chunk;
offset += chunk;
}
}
}
/**
* Writes the {@code toString()} value of each item in a collection to
* an {@code 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 {@code 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
* @deprecated 2.5 use {@link #writeLines(Collection, String, OutputStream, Charset)} instead
*/
@Deprecated
public static void writeLines(final Collection> lines, final String lineEnding,
final OutputStream output) throws IOException {
writeLines(lines, lineEnding, output, Charset.defaultCharset());
}
/**
* Writes the {@code toString()} value of each item in a collection to
* an {@code OutputStream} line by line, using the specified character
* encoding 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 {@code OutputStream} to write to, not null, not closed
* @param charset the charset to use, null means platform default
* @throws NullPointerException if the output is null
* @throws IOException if an I/O error occurs
* @since 2.3
*/
public static void writeLines(final Collection> lines, String lineEnding, final OutputStream output,
final Charset charset) throws IOException {
if (lines == null) {
return;
}
if (lineEnding == null) {
lineEnding = System.lineSeparator();
}
final Charset cs = Charsets.toCharset(charset);
for (final Object line : lines) {
if (line != null) {
output.write(line.toString().getBytes(cs));
}
output.write(lineEnding.getBytes(cs));
}
}
/**
* Writes the {@code toString()} value of each item in a collection to
* an {@code 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 {@code OutputStream} to write to, not null, not closed
* @param charsetName the name of the requested charset, null means platform default
* @throws NullPointerException if the output is null
* @throws IOException if an I/O error occurs
* @throws java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the
* encoding is not supported.
* @since 1.1
*/
public static void writeLines(final Collection> lines, final String lineEnding,
final OutputStream output, final String charsetName) throws IOException {
writeLines(lines, lineEnding, output, Charsets.toCharset(charsetName));
}
/**
* Writes the {@code toString()} value of each item in a collection to
* a {@code 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 {@code 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(final Collection> lines, String lineEnding,
final Writer writer) throws IOException {
if (lines == null) {
return;
}
if (lineEnding == null) {
lineEnding = System.lineSeparator();
}
for (final Object line : lines) {
if (line != null) {
writer.write(line.toString());
}
writer.write(lineEnding);
}
}
/**
* Returns the given Appendable if it is already a {@link Writer}, otherwise creates a Writer wrapper around the
* given Appendable.
*
* @param appendable the Appendable to wrap or return (not null)
* @return the given Appendable or a Writer wrapper around the given Appendable
* @throws NullPointerException if the input parameter is null
* @since 2.7
*/
public static Writer writer(final Appendable appendable) {
Objects.requireNonNull(appendable, "appendable");
if (appendable instanceof Writer) {
return (Writer) appendable;
}
if (appendable instanceof StringBuilder) {
return new StringBuilderWriter((StringBuilder) appendable);
}
return new AppendableWriter<>(appendable);
}
/**
* Instances should NOT be constructed in standard programming.
*/
public IOUtils() { //NOSONAR
}
}
* Closeable closeable = null;
* try {
* closeable = new FileReader("foo.txt");
* // process closeable
* closeable.close();
* } catch (Exception e) {
* // error handling
* } finally {
* IOUtils.closeQuietly(closeable);
* }
*
*
* try {
* return IOUtils.copy(inputStream, outputStream);
* } finally {
* IOUtils.closeQuietly(inputStream);
* IOUtils.closeQuietly(outputStream);
* }
*
*
* It should not be used to replace the close statement(s)
* which should be present for the non-exceptional case.
*
* It is only intended to simplify tidying up where normal processing has already failed
* and reporting close failure as well is not necessary or useful.
*
* Closeable closeable = null;
* try {
* closeable = new FileReader("foo.txt");
* // processing using the closeable; may throw an Exception
* closeable.close(); // Normal close - exceptions not ignored
* } catch (Exception e) {
* // error handling
* } finally {
* IOUtils.closeQuietly(closeable); // In case normal close was skipped due to Exception
* }
*
*
*
* try {
* return IOUtils.copy(inputStream, outputStream);
* } finally {
* IOUtils.closeQuietly(inputStream, outputStream);
* }
*
*
* 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);
* }
*
*
* 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);
* }
*
*
* 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);
* }
*
*
* Selector selector = null;
* try {
* selector = Selector.open();
* // process socket
*
* } catch (Exception e) {
* // error handling
* } finally {
* IOUtils.closeQuietly(selector);
* }
*
*
* ServerSocket socket = null;
* try {
* socket = new ServerSocket();
* // process socket
* socket.close();
* } catch (Exception e) {
* // error handling
* } finally {
* IOUtils.closeQuietly(socket);
* }
*
*
* 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);
* }
*
*
* 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);
* }
*
*
* try {
* LineIterator it = IOUtils.lineIterator(stream, charset);
* while (it.hasNext()) {
* String line = it.nextLine();
* /// do something with line
* }
* } finally {
* IOUtils.closeQuietly(stream);
* }
*
*
* @param input the {@code InputStream} to read from, not null
* @param charset the charset to use, null means platform default
* @return an Iterator of the lines in the reader, never null
* @throws IllegalArgumentException if the input is null
* @since 2.3
*/
public static LineIterator lineIterator(final InputStream input, final Charset charset) {
return new LineIterator(new InputStreamReader(input, Charsets.toCharset(charset)));
}
/**
* Returns an Iterator for the lines in an {@code InputStream}, using
* the character encoding specified (or default encoding if null).
*
* 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 {@code InputStream} to read from, not null
* @param charsetName 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 java.nio.charset.UnsupportedCharsetException thrown instead of {@link java.io
* .UnsupportedEncodingException} in version 2.2 if the
* encoding is not supported.
* @since 1.2
*/
public static LineIterator lineIterator(final InputStream input, final String charsetName) {
return lineIterator(input, Charsets.toCharset(charsetName));
}
/**
* Returns an Iterator for the lines in a {@code Reader}.
*
* try {
* LineIterator it = IOUtils.lineIterator(reader);
* while (it.hasNext()) {
* String line = it.nextLine();
* /// do something with line
* }
* } finally {
* IOUtils.closeQuietly(reader);
* }
*
*
* @param reader the {@code 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(final Reader reader) {
return new LineIterator(reader);
}
/**
* Reads 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(final InputStream input, final byte[] buffer) throws IOException {
return read(input, buffer, 0, buffer.length);
}
/**
* Reads 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 initial 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(final InputStream input, final byte[] buffer, final int offset, final int length)
throws IOException {
if (length < 0) {
throw new IllegalArgumentException("Length must not be negative: " + length);
}
int remaining = length;
while (remaining > 0) {
final int location = length - remaining;
final int count = input.read(buffer, offset + location, remaining);
if (EOF == count) { // EOF
break;
}
remaining -= count;
}
return length - remaining;
}
/**
* Reads bytes from a ReadableByteChannel.
*
*
* 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
* {@code 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(final InputStream input) throws IOException {
return ByteArrayOutputStream.toBufferedInputStream(input);
}
/**
* Fetches entire contents of an {@code InputStream} and represent
* same data as result InputStream.
*
*
* 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
* {@code BufferedInputStream}.
*
* @param input Stream to be fully buffered.
* @param size the initial buffer size
* @return A fully buffered stream.
* @throws IOException if an I/O error occurs.
* @since 2.5
*/
public static InputStream toBufferedInputStream(final InputStream input, final int size) throws IOException {
return ByteArrayOutputStream.toBufferedInputStream(input, size);
}
/**
* Returns the given reader if it is a {@link BufferedReader}, otherwise creates a BufferedReader from the given
* reader.
*
* @param reader the reader to wrap or return (not null)
* @return the given reader or a new {@link BufferedReader} for the given reader
* @throws NullPointerException if the input parameter is null
* @see #buffer(Reader)
* @since 2.2
*/
public static BufferedReader toBufferedReader(final Reader reader) {
return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);
}
/**
* Returns the given reader if it is a {@link BufferedReader}, otherwise creates a BufferedReader from the given
* reader.
*
* @param reader the reader to wrap or return (not null)
* @param size the buffer size, if a new BufferedReader is created.
* @return the given reader or a new {@link BufferedReader} for the given reader
* @throws NullPointerException if the input parameter is null
* @see #buffer(Reader)
* @since 2.5
*/
public static BufferedReader toBufferedReader(final Reader reader, final int size) {
return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader, size);
}
/**
* Gets the contents of an {@code InputStream} as a {@code byte[]}.
*