IOUtils.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.io;

  18. import java.io.BufferedInputStream;
  19. import java.io.BufferedOutputStream;
  20. import java.io.BufferedReader;
  21. import java.io.BufferedWriter;
  22. import java.io.ByteArrayInputStream;
  23. import java.io.CharArrayWriter;
  24. import java.io.Closeable;
  25. import java.io.EOFException;
  26. import java.io.File;
  27. import java.io.IOException;
  28. import java.io.InputStream;
  29. import java.io.InputStreamReader;
  30. import java.io.OutputStream;
  31. import java.io.OutputStreamWriter;
  32. import java.io.PipedInputStream;
  33. import java.io.PipedOutputStream;
  34. import java.io.Reader;
  35. import java.io.UncheckedIOException;
  36. import java.io.Writer;
  37. import java.net.HttpURLConnection;
  38. import java.net.ServerSocket;
  39. import java.net.Socket;
  40. import java.net.URI;
  41. import java.net.URL;
  42. import java.net.URLConnection;
  43. import java.nio.ByteBuffer;
  44. import java.nio.CharBuffer;
  45. import java.nio.channels.Channels;
  46. import java.nio.channels.ReadableByteChannel;
  47. import java.nio.channels.Selector;
  48. import java.nio.charset.Charset;
  49. import java.nio.charset.StandardCharsets;
  50. import java.nio.file.Files;
  51. import java.util.Arrays;
  52. import java.util.Collection;
  53. import java.util.Iterator;
  54. import java.util.List;
  55. import java.util.Objects;
  56. import java.util.function.Consumer;
  57. import java.util.function.Supplier;
  58. import java.util.stream.Collectors;
  59. import java.util.stream.Stream;
  60. import java.util.zip.InflaterInputStream;

  61. import org.apache.commons.io.channels.FileChannels;
  62. import org.apache.commons.io.function.IOConsumer;
  63. import org.apache.commons.io.function.IOSupplier;
  64. import org.apache.commons.io.function.IOTriFunction;
  65. import org.apache.commons.io.input.CharSequenceReader;
  66. import org.apache.commons.io.input.QueueInputStream;
  67. import org.apache.commons.io.output.AppendableWriter;
  68. import org.apache.commons.io.output.ByteArrayOutputStream;
  69. import org.apache.commons.io.output.NullOutputStream;
  70. import org.apache.commons.io.output.NullWriter;
  71. import org.apache.commons.io.output.StringBuilderWriter;
  72. import org.apache.commons.io.output.ThresholdingOutputStream;
  73. import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;

  74. /**
  75.  * General IO stream manipulation utilities.
  76.  * <p>
  77.  * This class provides static utility methods for input/output operations.
  78.  * </p>
  79.  * <ul>
  80.  * <li>closeQuietly - these methods close a stream ignoring nulls and exceptions
  81.  * <li>toXxx/read - these methods read data from a stream
  82.  * <li>write - these methods write data to a stream
  83.  * <li>copy - these methods copy all the data from one stream to another
  84.  * <li>contentEquals - these methods compare the content of two streams
  85.  * </ul>
  86.  * <p>
  87.  * The byte-to-char methods and char-to-byte methods involve a conversion step.
  88.  * Two methods are provided in each case, one that uses the platform default
  89.  * encoding and the other which allows you to specify an encoding. You are
  90.  * encouraged to always specify an encoding because relying on the platform
  91.  * default can lead to unexpected results, for example when moving from
  92.  * development to production.
  93.  * </p>
  94.  * <p>
  95.  * All the methods in this class that read a stream are buffered internally.
  96.  * This means that there is no cause to use a {@link BufferedInputStream}
  97.  * or {@link BufferedReader}. The default buffer size of 4K has been shown
  98.  * to be efficient in tests.
  99.  * </p>
  100.  * <p>
  101.  * The various copy methods all delegate the actual copying to one of the following methods:
  102.  * </p>
  103.  * <ul>
  104.  * <li>{@link #copyLarge(InputStream, OutputStream, byte[])}</li>
  105.  * <li>{@link #copyLarge(InputStream, OutputStream, long, long, byte[])}</li>
  106.  * <li>{@link #copyLarge(Reader, Writer, char[])}</li>
  107.  * <li>{@link #copyLarge(Reader, Writer, long, long, char[])}</li>
  108.  * </ul>
  109.  * For example, {@link #copy(InputStream, OutputStream)} calls {@link #copyLarge(InputStream, OutputStream)}
  110.  * which calls {@link #copy(InputStream, OutputStream, int)} which creates the buffer and calls
  111.  * {@link #copyLarge(InputStream, OutputStream, byte[])}.
  112.  * <p>
  113.  * Applications can re-use buffers by using the underlying methods directly.
  114.  * This may improve performance for applications that need to do a lot of copying.
  115.  * </p>
  116.  * <p>
  117.  * Wherever possible, the methods in this class do <em>not</em> flush or close
  118.  * the stream. This is to avoid making non-portable assumptions about the
  119.  * streams' origin and further use. Thus the caller is still responsible for
  120.  * closing streams after use.
  121.  * </p>
  122.  * <p>
  123.  * Provenance: Excalibur.
  124.  * </p>
  125.  */
  126. public class IOUtils {
  127.     // NOTE: This class is focused on InputStream, OutputStream, Reader and
  128.     // Writer. Each method should take at least one of these as a parameter,
  129.     // or return one of them.

  130.     /**
  131.      * CR char '{@value}'.
  132.      *
  133.      * @since 2.9.0
  134.      */
  135.     public static final int CR = '\r';

  136.     /**
  137.      * The default buffer size ({@value}) to use in copy methods.
  138.      */
  139.     public static final int DEFAULT_BUFFER_SIZE = 8192;

  140.     /**
  141.      * The system directory separator character.
  142.      */
  143.     public static final char DIR_SEPARATOR = File.separatorChar;

  144.     /**
  145.      * The Unix directory separator character '{@value}'.
  146.      */
  147.     public static final char DIR_SEPARATOR_UNIX = '/';

  148.     /**
  149.      * The Windows directory separator character '{@value}'.
  150.      */
  151.     public static final char DIR_SEPARATOR_WINDOWS = '\\';

  152.     /**
  153.      * A singleton empty byte array.
  154.      *
  155.      *  @since 2.9.0
  156.      */
  157.     public static final byte[] EMPTY_BYTE_ARRAY = {};

  158.     /**
  159.      * Represents the end-of-file (or stream) value {@value}.
  160.      * @since 2.5 (made public)
  161.      */
  162.     public static final int EOF = -1;

  163.     /**
  164.      * LF char '{@value}'.
  165.      *
  166.      * @since 2.9.0
  167.      */
  168.     public static final int LF = '\n';

  169.     /**
  170.      * The system line separator string.
  171.      *
  172.      * @deprecated Use {@link System#lineSeparator()}.
  173.      */
  174.     @Deprecated
  175.     public static final String LINE_SEPARATOR = System.lineSeparator();

  176.     /**
  177.      * The Unix line separator string.
  178.      *
  179.      * @see StandardLineSeparator#LF
  180.      */
  181.     public static final String LINE_SEPARATOR_UNIX = StandardLineSeparator.LF.getString();

  182.     /**
  183.      * The Windows line separator string.
  184.      *
  185.      * @see StandardLineSeparator#CRLF
  186.      */
  187.     public static final String LINE_SEPARATOR_WINDOWS = StandardLineSeparator.CRLF.getString();

  188.     /**
  189.      * Internal byte array buffer, intended for both reading and writing.
  190.      */
  191.     private static final ThreadLocal<byte[]> SCRATCH_BYTE_BUFFER_RW = ThreadLocal.withInitial(IOUtils::byteArray);

  192.     /**
  193.      * Internal byte array buffer, intended for write only operations.
  194.      */
  195.     private static final byte[] SCRATCH_BYTE_BUFFER_WO = byteArray();

  196.     /**
  197.      * Internal char array buffer, intended for both reading and writing.
  198.      */
  199.     private static final ThreadLocal<char[]> SCRATCH_CHAR_BUFFER_RW = ThreadLocal.withInitial(IOUtils::charArray);

  200.     /**
  201.      * Internal char array buffer, intended for write only operations.
  202.      */
  203.     private static final char[] SCRATCH_CHAR_BUFFER_WO = charArray();

  204.     /**
  205.      * Returns the given InputStream if it is already a {@link BufferedInputStream}, otherwise creates a
  206.      * BufferedInputStream from the given InputStream.
  207.      *
  208.      * @param inputStream the InputStream to wrap or return (not null)
  209.      * @return the given InputStream or a new {@link BufferedInputStream} for the given InputStream
  210.      * @throws NullPointerException if the input parameter is null
  211.      * @since 2.5
  212.      */
  213.     @SuppressWarnings("resource") // parameter null check
  214.     public static BufferedInputStream buffer(final InputStream inputStream) {
  215.         // reject null early on rather than waiting for IO operation to fail
  216.         // not checked by BufferedInputStream
  217.         Objects.requireNonNull(inputStream, "inputStream");
  218.         return inputStream instanceof BufferedInputStream ?
  219.                 (BufferedInputStream) inputStream : new BufferedInputStream(inputStream);
  220.     }

  221.     /**
  222.      * Returns the given InputStream if it is already a {@link BufferedInputStream}, otherwise creates a
  223.      * BufferedInputStream from the given InputStream.
  224.      *
  225.      * @param inputStream the InputStream to wrap or return (not null)
  226.      * @param size the buffer size, if a new BufferedInputStream is created.
  227.      * @return the given InputStream or a new {@link BufferedInputStream} for the given InputStream
  228.      * @throws NullPointerException if the input parameter is null
  229.      * @since 2.5
  230.      */
  231.     @SuppressWarnings("resource") // parameter null check
  232.     public static BufferedInputStream buffer(final InputStream inputStream, final int size) {
  233.         // reject null early on rather than waiting for IO operation to fail
  234.         // not checked by BufferedInputStream
  235.         Objects.requireNonNull(inputStream, "inputStream");
  236.         return inputStream instanceof BufferedInputStream ?
  237.                 (BufferedInputStream) inputStream : new BufferedInputStream(inputStream, size);
  238.     }

  239.     /**
  240.      * Returns the given OutputStream if it is already a {@link BufferedOutputStream}, otherwise creates a
  241.      * BufferedOutputStream from the given OutputStream.
  242.      *
  243.      * @param outputStream the OutputStream to wrap or return (not null)
  244.      * @return the given OutputStream or a new {@link BufferedOutputStream} for the given OutputStream
  245.      * @throws NullPointerException if the input parameter is null
  246.      * @since 2.5
  247.      */
  248.     @SuppressWarnings("resource") // parameter null check
  249.     public static BufferedOutputStream buffer(final OutputStream outputStream) {
  250.         // reject null early on rather than waiting for IO operation to fail
  251.         // not checked by BufferedInputStream
  252.         Objects.requireNonNull(outputStream, "outputStream");
  253.         return outputStream instanceof BufferedOutputStream ?
  254.                 (BufferedOutputStream) outputStream : new BufferedOutputStream(outputStream);
  255.     }

  256.     /**
  257.      * Returns the given OutputStream if it is already a {@link BufferedOutputStream}, otherwise creates a
  258.      * BufferedOutputStream from the given OutputStream.
  259.      *
  260.      * @param outputStream the OutputStream to wrap or return (not null)
  261.      * @param size the buffer size, if a new BufferedOutputStream is created.
  262.      * @return the given OutputStream or a new {@link BufferedOutputStream} for the given OutputStream
  263.      * @throws NullPointerException if the input parameter is null
  264.      * @since 2.5
  265.      */
  266.     @SuppressWarnings("resource") // parameter null check
  267.     public static BufferedOutputStream buffer(final OutputStream outputStream, final int size) {
  268.         // reject null early on rather than waiting for IO operation to fail
  269.         // not checked by BufferedInputStream
  270.         Objects.requireNonNull(outputStream, "outputStream");
  271.         return outputStream instanceof BufferedOutputStream ?
  272.                 (BufferedOutputStream) outputStream : new BufferedOutputStream(outputStream, size);
  273.     }

  274.     /**
  275.      * Returns the given reader if it is already a {@link BufferedReader}, otherwise creates a BufferedReader from
  276.      * the given reader.
  277.      *
  278.      * @param reader the reader to wrap or return (not null)
  279.      * @return the given reader or a new {@link BufferedReader} for the given reader
  280.      * @throws NullPointerException if the input parameter is null
  281.      * @since 2.5
  282.      */
  283.     public static BufferedReader buffer(final Reader reader) {
  284.         return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);
  285.     }

  286.     /**
  287.      * Returns the given reader if it is already a {@link BufferedReader}, otherwise creates a BufferedReader from the
  288.      * given reader.
  289.      *
  290.      * @param reader the reader to wrap or return (not null)
  291.      * @param size the buffer size, if a new BufferedReader is created.
  292.      * @return the given reader or a new {@link BufferedReader} for the given reader
  293.      * @throws NullPointerException if the input parameter is null
  294.      * @since 2.5
  295.      */
  296.     public static BufferedReader buffer(final Reader reader, final int size) {
  297.         return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader, size);
  298.     }

  299.     /**
  300.      * Returns the given Writer if it is already a {@link BufferedWriter}, otherwise creates a BufferedWriter from the
  301.      * given Writer.
  302.      *
  303.      * @param writer the Writer to wrap or return (not null)
  304.      * @return the given Writer or a new {@link BufferedWriter} for the given Writer
  305.      * @throws NullPointerException if the input parameter is null
  306.      * @since 2.5
  307.      */
  308.     public static BufferedWriter buffer(final Writer writer) {
  309.         return writer instanceof BufferedWriter ? (BufferedWriter) writer : new BufferedWriter(writer);
  310.     }

  311.     /**
  312.      * Returns the given Writer if it is already a {@link BufferedWriter}, otherwise creates a BufferedWriter from the
  313.      * given Writer.
  314.      *
  315.      * @param writer the Writer to wrap or return (not null)
  316.      * @param size the buffer size, if a new BufferedWriter is created.
  317.      * @return the given Writer or a new {@link BufferedWriter} for the given Writer
  318.      * @throws NullPointerException if the input parameter is null
  319.      * @since 2.5
  320.      */
  321.     public static BufferedWriter buffer(final Writer writer, final int size) {
  322.         return writer instanceof BufferedWriter ? (BufferedWriter) writer : new BufferedWriter(writer, size);
  323.     }

  324.     /**
  325.      * Returns a new byte array of size {@link #DEFAULT_BUFFER_SIZE}.
  326.      *
  327.      * @return a new byte array of size {@link #DEFAULT_BUFFER_SIZE}.
  328.      * @since 2.9.0
  329.      */
  330.     public static byte[] byteArray() {
  331.         return byteArray(DEFAULT_BUFFER_SIZE);
  332.     }

  333.     /**
  334.      * Returns a new byte array of the given size.
  335.      *
  336.      * TODO Consider guarding or warning against large allocations...
  337.      *
  338.      * @param size array size.
  339.      * @return a new byte array of the given size.
  340.      * @throws NegativeArraySizeException if the size is negative.
  341.      * @since 2.9.0
  342.      */
  343.     public static byte[] byteArray(final int size) {
  344.         return new byte[size];
  345.     }

  346.     /**
  347.      * Returns a new char array of size {@link #DEFAULT_BUFFER_SIZE}.
  348.      *
  349.      * @return a new char array of size {@link #DEFAULT_BUFFER_SIZE}.
  350.      * @since 2.9.0
  351.      */
  352.     private static char[] charArray() {
  353.         return charArray(DEFAULT_BUFFER_SIZE);
  354.     }

  355.     /**
  356.      * Returns a new char array of the given size.
  357.      *
  358.      * TODO Consider guarding or warning against large allocations...
  359.      *
  360.      * @param size array size.
  361.      * @return a new char array of the given size.
  362.      * @since 2.9.0
  363.      */
  364.     private static char[] charArray(final int size) {
  365.         return new char[size];
  366.     }

  367.     /**
  368.      * Clears any state.
  369.      * <ul>
  370.      * <li>Removes the current thread's value for thread-local variables.</li>
  371.      * <li>Sets static scratch arrays to 0s.</li>
  372.      * </ul>
  373.      * @see IO#clear()
  374.      */
  375.     static void clear() {
  376.         SCRATCH_BYTE_BUFFER_RW.remove();
  377.         SCRATCH_CHAR_BUFFER_RW.remove();
  378.         Arrays.fill(SCRATCH_BYTE_BUFFER_WO, (byte) 0);
  379.         Arrays.fill(SCRATCH_CHAR_BUFFER_WO, (char) 0);
  380.     }

  381.     /**
  382.      * Closes the given {@link Closeable} as a null-safe operation.
  383.      *
  384.      * @param closeable The resource to close, may be null.
  385.      * @throws IOException if an I/O error occurs.
  386.      * @since 2.7
  387.      */
  388.     public static void close(final Closeable closeable) throws IOException {
  389.         if (closeable != null) {
  390.             closeable.close();
  391.         }
  392.     }

  393.     /**
  394.      * Closes the given {@link Closeable}s as null-safe operations.
  395.      *
  396.      * @param closeables The resource(s) to close, may be null.
  397.      * @throws IOExceptionList if an I/O error occurs.
  398.      * @since 2.8.0
  399.      */
  400.     public static void close(final Closeable... closeables) throws IOExceptionList {
  401.         IOConsumer.forAll(IOUtils::close, closeables);
  402.     }

  403.     /**
  404.      * Closes the given {@link Closeable} as a null-safe operation.
  405.      *
  406.      * @param closeable The resource to close, may be null.
  407.      * @param consumer Consume the IOException thrown by {@link Closeable#close()}.
  408.      * @throws IOException if an I/O error occurs.
  409.      * @since 2.7
  410.      */
  411.     public static void close(final Closeable closeable, final IOConsumer<IOException> consumer) throws IOException {
  412.         if (closeable != null) {
  413.             try {
  414.                 closeable.close();
  415.             } catch (final IOException e) {
  416.                 if (consumer != null) {
  417.                     consumer.accept(e);
  418.                 }
  419.             } catch (final Exception e) {
  420.                 if (consumer != null) {
  421.                     consumer.accept(new IOException(e));
  422.                 }
  423.             }
  424.         }
  425.     }

  426.     /**
  427.      * Closes a URLConnection.
  428.      *
  429.      * @param conn the connection to close.
  430.      * @since 2.4
  431.      */
  432.     public static void close(final URLConnection conn) {
  433.         if (conn instanceof HttpURLConnection) {
  434.             ((HttpURLConnection) conn).disconnect();
  435.         }
  436.     }

  437.     /**
  438.      * Avoids the need to type cast.
  439.      *
  440.      * @param closeable the object to close, may be null
  441.      */
  442.     private static void closeQ(final Closeable closeable) {
  443.         closeQuietly(closeable, null);
  444.     }

  445.     /**
  446.      * Closes a {@link Closeable} unconditionally.
  447.      *
  448.      * <p>
  449.      * Equivalent to {@link Closeable#close()}, except any exceptions will be ignored. This is typically used in
  450.      * finally blocks.
  451.      * <p>
  452.      * Example code:
  453.      * </p>
  454.      * <pre>
  455.      * Closeable closeable = null;
  456.      * try {
  457.      *     closeable = new FileReader(&quot;foo.txt&quot;);
  458.      *     // process closeable
  459.      *     closeable.close();
  460.      * } catch (Exception e) {
  461.      *     // error handling
  462.      * } finally {
  463.      *     IOUtils.closeQuietly(closeable);
  464.      * }
  465.      * </pre>
  466.      * <p>
  467.      * Closing all streams:
  468.      * </p>
  469.      * <pre>
  470.      * try {
  471.      *     return IOUtils.copy(inputStream, outputStream);
  472.      * } finally {
  473.      *     IOUtils.closeQuietly(inputStream);
  474.      *     IOUtils.closeQuietly(outputStream);
  475.      * }
  476.      * </pre>
  477.      * <p>
  478.      * Also consider using a try-with-resources statement where appropriate.
  479.      * </p>
  480.      *
  481.      * @param closeable the objects to close, may be null or already closed
  482.      * @since 2.0
  483.      * @see Throwable#addSuppressed(Throwable)
  484.      */
  485.     public static void closeQuietly(final Closeable closeable) {
  486.         closeQuietly(closeable, null);
  487.     }

  488.     /**
  489.      * Closes a {@link Closeable} unconditionally.
  490.      * <p>
  491.      * Equivalent to {@link Closeable#close()}, except any exceptions will be ignored.
  492.      * <p>
  493.      * This is typically used in finally blocks to ensure that the closeable is closed
  494.      * even if an Exception was thrown before the normal close statement was reached.
  495.      * <br>
  496.      * <b>It should not be used to replace the close statement(s)
  497.      * which should be present for the non-exceptional case.</b>
  498.      * <br>
  499.      * It is only intended to simplify tidying up where normal processing has already failed
  500.      * and reporting close failure as well is not necessary or useful.
  501.      * <p>
  502.      * Example code:
  503.      * </p>
  504.      * <pre>
  505.      * Closeable closeable = null;
  506.      * try {
  507.      *     closeable = new FileReader(&quot;foo.txt&quot;);
  508.      *     // processing using the closeable; may throw an Exception
  509.      *     closeable.close(); // Normal close - exceptions not ignored
  510.      * } catch (Exception e) {
  511.      *     // error handling
  512.      * } finally {
  513.      *     <strong>IOUtils.closeQuietly(closeable); // In case normal close was skipped due to Exception</strong>
  514.      * }
  515.      * </pre>
  516.      * <p>
  517.      * Closing all streams:
  518.      * <br>
  519.      * <pre>
  520.      * try {
  521.      *     return IOUtils.copy(inputStream, outputStream);
  522.      * } finally {
  523.      *     IOUtils.closeQuietly(inputStream, outputStream);
  524.      * }
  525.      * </pre>
  526.      * <p>
  527.      * Also consider using a try-with-resources statement where appropriate.
  528.      * </p>
  529.      * @param closeables the objects to close, may be null or already closed
  530.      * @see #closeQuietly(Closeable)
  531.      * @since 2.5
  532.      * @see Throwable#addSuppressed(Throwable)
  533.      */
  534.     public static void closeQuietly(final Closeable... closeables) {
  535.         if (closeables != null) {
  536.             closeQuietly(Arrays.stream(closeables));
  537.         }
  538.     }

  539.     /**
  540.      * Closes the given {@link Closeable} as a null-safe operation while consuming IOException by the given {@code consumer}.
  541.      *
  542.      * @param closeable The resource to close, may be null.
  543.      * @param consumer Consumes the Exception thrown by {@link Closeable#close()}.
  544.      * @since 2.7
  545.      */
  546.     public static void closeQuietly(final Closeable closeable, final Consumer<Exception> consumer) {
  547.         if (closeable != null) {
  548.             try {
  549.                 closeable.close();
  550.             } catch (final Exception e) {
  551.                 if (consumer != null) {
  552.                     consumer.accept(e);
  553.                 }
  554.             }
  555.         }
  556.     }

  557.     /**
  558.      * Closes an {@link InputStream} unconditionally.
  559.      * <p>
  560.      * Equivalent to {@link InputStream#close()}, except any exceptions will be ignored.
  561.      * This is typically used in finally blocks.
  562.      * </p>
  563.      * <p>
  564.      * Example code:
  565.      * </p>
  566.      * <pre>
  567.      *   byte[] data = new byte[1024];
  568.      *   InputStream in = null;
  569.      *   try {
  570.      *       in = new FileInputStream("foo.txt");
  571.      *       in.read(data);
  572.      *       in.close(); //close errors are handled
  573.      *   } catch (Exception e) {
  574.      *       // error handling
  575.      *   } finally {
  576.      *       IOUtils.closeQuietly(in);
  577.      *   }
  578.      * </pre>
  579.      * <p>
  580.      * Also consider using a try-with-resources statement where appropriate.
  581.      * </p>
  582.      *
  583.      * @param input the InputStream to close, may be null or already closed
  584.      * @see Throwable#addSuppressed(Throwable)
  585.      */
  586.     public static void closeQuietly(final InputStream input) {
  587.         closeQ(input);
  588.     }

  589.     /**
  590.      * Closes an iterable of {@link Closeable} unconditionally.
  591.      * <p>
  592.      * Equivalent calling {@link Closeable#close()} on each element, except any exceptions will be ignored.
  593.      * </p>
  594.      *
  595.      * @param closeables the objects to close, may be null or already closed
  596.      * @see #closeQuietly(Closeable)
  597.      * @since 2.12.0
  598.      */
  599.     public static void closeQuietly(final Iterable<Closeable> closeables) {
  600.         if (closeables != null) {
  601.             closeables.forEach(IOUtils::closeQuietly);
  602.         }
  603.     }

  604.     /**
  605.      * Closes an {@link OutputStream} unconditionally.
  606.      * <p>
  607.      * Equivalent to {@link OutputStream#close()}, except any exceptions will be ignored.
  608.      * This is typically used in finally blocks.
  609.      * </p>
  610.      * <p>
  611.      * Example code:
  612.      * </p>
  613.      * <pre>
  614.      * byte[] data = "Hello, World".getBytes();
  615.      *
  616.      * OutputStream out = null;
  617.      * try {
  618.      *     out = new FileOutputStream("foo.txt");
  619.      *     out.write(data);
  620.      *     out.close(); //close errors are handled
  621.      * } catch (IOException e) {
  622.      *     // error handling
  623.      * } finally {
  624.      *     IOUtils.closeQuietly(out);
  625.      * }
  626.      * </pre>
  627.      * <p>
  628.      * Also consider using a try-with-resources statement where appropriate.
  629.      * </p>
  630.      *
  631.      * @param output the OutputStream to close, may be null or already closed
  632.      * @see Throwable#addSuppressed(Throwable)
  633.      */
  634.     public static void closeQuietly(final OutputStream output) {
  635.         closeQ(output);
  636.     }

  637.     /**
  638.      * Closes an {@link Reader} unconditionally.
  639.      * <p>
  640.      * Equivalent to {@link Reader#close()}, except any exceptions will be ignored.
  641.      * This is typically used in finally blocks.
  642.      * </p>
  643.      * <p>
  644.      * Example code:
  645.      * </p>
  646.      * <pre>
  647.      *   char[] data = new char[1024];
  648.      *   Reader in = null;
  649.      *   try {
  650.      *       in = new FileReader("foo.txt");
  651.      *       in.read(data);
  652.      *       in.close(); //close errors are handled
  653.      *   } catch (Exception e) {
  654.      *       // error handling
  655.      *   } finally {
  656.      *       IOUtils.closeQuietly(in);
  657.      *   }
  658.      * </pre>
  659.      * <p>
  660.      * Also consider using a try-with-resources statement where appropriate.
  661.      * </p>
  662.      *
  663.      * @param reader the Reader to close, may be null or already closed
  664.      * @see Throwable#addSuppressed(Throwable)
  665.      */
  666.     public static void closeQuietly(final Reader reader) {
  667.         closeQ(reader);
  668.     }

  669.     /**
  670.      * Closes a {@link Selector} unconditionally.
  671.      * <p>
  672.      * Equivalent to {@link Selector#close()}, except any exceptions will be ignored.
  673.      * This is typically used in finally blocks.
  674.      * </p>
  675.      * <p>
  676.      * Example code:
  677.      * </p>
  678.      * <pre>
  679.      *   Selector selector = null;
  680.      *   try {
  681.      *       selector = Selector.open();
  682.      *       // process socket
  683.      *
  684.      *   } catch (Exception e) {
  685.      *       // error handling
  686.      *   } finally {
  687.      *       IOUtils.closeQuietly(selector);
  688.      *   }
  689.      * </pre>
  690.      * <p>
  691.      * Also consider using a try-with-resources statement where appropriate.
  692.      * </p>
  693.      *
  694.      * @param selector the Selector to close, may be null or already closed
  695.      * @since 2.2
  696.      * @see Throwable#addSuppressed(Throwable)
  697.      */
  698.     public static void closeQuietly(final Selector selector) {
  699.         closeQ(selector);
  700.     }

  701.     /**
  702.      * Closes a {@link ServerSocket} unconditionally.
  703.      * <p>
  704.      * Equivalent to {@link ServerSocket#close()}, except any exceptions will be ignored.
  705.      * This is typically used in finally blocks.
  706.      * </p>
  707.      * <p>
  708.      * Example code:
  709.      * </p>
  710.      * <pre>
  711.      *   ServerSocket socket = null;
  712.      *   try {
  713.      *       socket = new ServerSocket();
  714.      *       // process socket
  715.      *       socket.close();
  716.      *   } catch (Exception e) {
  717.      *       // error handling
  718.      *   } finally {
  719.      *       IOUtils.closeQuietly(socket);
  720.      *   }
  721.      * </pre>
  722.      * <p>
  723.      * Also consider using a try-with-resources statement where appropriate.
  724.      * </p>
  725.      *
  726.      * @param serverSocket the ServerSocket to close, may be null or already closed
  727.      * @since 2.2
  728.      * @see Throwable#addSuppressed(Throwable)
  729.      */
  730.     public static void closeQuietly(final ServerSocket serverSocket) {
  731.         closeQ(serverSocket);
  732.     }

  733.     /**
  734.      * Closes a {@link Socket} unconditionally.
  735.      * <p>
  736.      * Equivalent to {@link Socket#close()}, except any exceptions will be ignored.
  737.      * This is typically used in finally blocks.
  738.      * </p>
  739.      * <p>
  740.      * Example code:
  741.      * </p>
  742.      * <pre>
  743.      *   Socket socket = null;
  744.      *   try {
  745.      *       socket = new Socket("http://www.foo.com/", 80);
  746.      *       // process socket
  747.      *       socket.close();
  748.      *   } catch (Exception e) {
  749.      *       // error handling
  750.      *   } finally {
  751.      *       IOUtils.closeQuietly(socket);
  752.      *   }
  753.      * </pre>
  754.      * <p>
  755.      * Also consider using a try-with-resources statement where appropriate.
  756.      * </p>
  757.      *
  758.      * @param socket the Socket to close, may be null or already closed
  759.      * @since 2.0
  760.      * @see Throwable#addSuppressed(Throwable)
  761.      */
  762.     public static void closeQuietly(final Socket socket) {
  763.         closeQ(socket);
  764.     }

  765.     /**
  766.      * Closes a stream of {@link Closeable} unconditionally.
  767.      * <p>
  768.      * Equivalent calling {@link Closeable#close()} on each element, except any exceptions will be ignored.
  769.      * </p>
  770.      *
  771.      * @param closeables the objects to close, may be null or already closed
  772.      * @see #closeQuietly(Closeable)
  773.      * @since 2.12.0
  774.      */
  775.     public static void closeQuietly(final Stream<Closeable> closeables) {
  776.         if (closeables != null) {
  777.             closeables.forEach(IOUtils::closeQuietly);
  778.         }
  779.     }

  780.     /**
  781.      * Closes an {@link Writer} unconditionally.
  782.      * <p>
  783.      * Equivalent to {@link Writer#close()}, except any exceptions will be ignored.
  784.      * This is typically used in finally blocks.
  785.      * </p>
  786.      * <p>
  787.      * Example code:
  788.      * </p>
  789.      * <pre>
  790.      *   Writer out = null;
  791.      *   try {
  792.      *       out = new StringWriter();
  793.      *       out.write("Hello World");
  794.      *       out.close(); //close errors are handled
  795.      *   } catch (Exception e) {
  796.      *       // error handling
  797.      *   } finally {
  798.      *       IOUtils.closeQuietly(out);
  799.      *   }
  800.      * </pre>
  801.      * <p>
  802.      * Also consider using a try-with-resources statement where appropriate.
  803.      * </p>
  804.      *
  805.      * @param writer the Writer to close, may be null or already closed
  806.      * @see Throwable#addSuppressed(Throwable)
  807.      */
  808.     public static void closeQuietly(final Writer writer) {
  809.         closeQ(writer);
  810.     }

  811.     /**
  812.      * Consumes bytes from a {@link InputStream} and ignores them.
  813.      * <p>
  814.      * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
  815.      * </p>
  816.      *
  817.      * @param input the {@link InputStream} to read.
  818.      * @return the number of bytes copied. or {@code 0} if {@code input is null}.
  819.      * @throws NullPointerException if the InputStream is {@code null}.
  820.      * @throws IOException if an I/O error occurs.
  821.      * @since 2.8.0
  822.      */
  823.     public static long consume(final InputStream input) throws IOException {
  824.         return copyLarge(input, NullOutputStream.INSTANCE);
  825.     }

  826.     /**
  827.      * Consumes characters from a {@link Reader} and ignores them.
  828.      * <p>
  829.      * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
  830.      * </p>
  831.      *
  832.      * @param input the {@link Reader} to read.
  833.      * @return the number of bytes copied. or {@code 0} if {@code input is null}.
  834.      * @throws NullPointerException if the Reader is {@code null}.
  835.      * @throws IOException if an I/O error occurs.
  836.      * @since 2.12.0
  837.      */
  838.     public static long consume(final Reader input) throws IOException {
  839.         return copyLarge(input, NullWriter.INSTANCE);
  840.     }

  841.     /**
  842.      * Compares the contents of two Streams to determine if they are equal or
  843.      * not.
  844.      * <p>
  845.      * This method buffers the input internally using
  846.      * {@link BufferedInputStream} if they are not already buffered.
  847.      * </p>
  848.      *
  849.      * @param input1 the first stream
  850.      * @param input2 the second stream
  851.      * @return true if the content of the streams are equal or they both don't
  852.      * exist, false otherwise
  853.      * @throws IOException          if an I/O error occurs
  854.      */
  855.     @SuppressWarnings("resource") // Caller closes input streams
  856.     public static boolean contentEquals(final InputStream input1, final InputStream input2) throws IOException {
  857.         // Before making any changes, please test with org.apache.commons.io.jmh.IOUtilsContentEqualsInputStreamsBenchmark
  858.         if (input1 == input2) {
  859.             return true;
  860.         }
  861.         if (input1 == null || input2 == null) {
  862.             return false;
  863.         }
  864.         // We do not close FileChannels because that closes the owning InputStream.
  865.         return FileChannels.contentEquals(Channels.newChannel(input1), Channels.newChannel(input2), DEFAULT_BUFFER_SIZE);
  866.     }

  867.     // TODO Consider making public
  868.     private static boolean contentEquals(final Iterator<?> iterator1, final Iterator<?> iterator2) {
  869.         while (iterator1.hasNext()) {
  870.             if (!iterator2.hasNext()) {
  871.                 return false;
  872.             }
  873.             if (!Objects.equals(iterator1.next(), iterator2.next())) {
  874.                 return false;
  875.             }
  876.         }
  877.         return !iterator2.hasNext();
  878.     }

  879.     /**
  880.      * Compares the contents of two Readers to determine if they are equal or not.
  881.      * <p>
  882.      * This method buffers the input internally using {@link BufferedReader} if they are not already buffered.
  883.      * </p>
  884.      *
  885.      * @param input1 the first reader
  886.      * @param input2 the second reader
  887.      * @return true if the content of the readers are equal or they both don't exist, false otherwise
  888.      * @throws NullPointerException if either input is null
  889.      * @throws IOException if an I/O error occurs
  890.      * @since 1.1
  891.      */
  892.     public static boolean contentEquals(final Reader input1, final Reader input2) throws IOException {
  893.         if (input1 == input2) {
  894.             return true;
  895.         }
  896.         if (input1 == null || input2 == null) {
  897.             return false;
  898.         }

  899.         // reuse one
  900.         final char[] array1 = getScratchCharArray();
  901.         // but allocate another
  902.         final char[] array2 = charArray();
  903.         int pos1;
  904.         int pos2;
  905.         int count1;
  906.         int count2;
  907.         while (true) {
  908.             pos1 = 0;
  909.             pos2 = 0;
  910.             for (int index = 0; index < DEFAULT_BUFFER_SIZE; index++) {
  911.                 if (pos1 == index) {
  912.                     do {
  913.                         count1 = input1.read(array1, pos1, DEFAULT_BUFFER_SIZE - pos1);
  914.                     } while (count1 == 0);
  915.                     if (count1 == EOF) {
  916.                         return pos2 == index && input2.read() == EOF;
  917.                     }
  918.                     pos1 += count1;
  919.                 }
  920.                 if (pos2 == index) {
  921.                     do {
  922.                         count2 = input2.read(array2, pos2, DEFAULT_BUFFER_SIZE - pos2);
  923.                     } while (count2 == 0);
  924.                     if (count2 == EOF) {
  925.                         return pos1 == index && input1.read() == EOF;
  926.                     }
  927.                     pos2 += count2;
  928.                 }
  929.                 if (array1[index] != array2[index]) {
  930.                     return false;
  931.                 }
  932.             }
  933.         }
  934.     }

  935.     // TODO Consider making public
  936.     private static boolean contentEquals(final Stream<?> stream1, final Stream<?> stream2) {
  937.         if (stream1 == stream2) {
  938.             return true;
  939.         }
  940.         if (stream1 == null || stream2 == null) {
  941.             return false;
  942.         }
  943.         return contentEquals(stream1.iterator(), stream2.iterator());
  944.     }

  945.     // TODO Consider making public
  946.     private static boolean contentEqualsIgnoreEOL(final BufferedReader reader1, final BufferedReader reader2) {
  947.         if (reader1 == reader2) {
  948.             return true;
  949.         }
  950.         if (reader1 == null || reader2 == null) {
  951.             return false;
  952.         }
  953.         return contentEquals(reader1.lines(), reader2.lines());
  954.     }

  955.     /**
  956.      * Compares the contents of two Readers to determine if they are equal or
  957.      * not, ignoring EOL characters.
  958.      * <p>
  959.      * This method buffers the input internally using
  960.      * {@link BufferedReader} if they are not already buffered.
  961.      * </p>
  962.      *
  963.      * @param reader1 the first reader
  964.      * @param reader2 the second reader
  965.      * @return true if the content of the readers are equal (ignoring EOL differences),  false otherwise
  966.      * @throws NullPointerException if either input is null
  967.      * @throws UncheckedIOException if an I/O error occurs
  968.      * @since 2.2
  969.      */
  970.     @SuppressWarnings("resource")
  971.     public static boolean contentEqualsIgnoreEOL(final Reader reader1, final Reader reader2) throws UncheckedIOException {
  972.         if (reader1 == reader2) {
  973.             return true;
  974.         }
  975.         if (reader1 == null || reader2 == null) {
  976.             return false;
  977.         }
  978.         return contentEqualsIgnoreEOL(toBufferedReader(reader1), toBufferedReader(reader2));
  979.     }

  980.     /**
  981.      * Copies bytes from an {@link InputStream} to an {@link OutputStream}.
  982.      * <p>
  983.      * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
  984.      * </p>
  985.      * <p>
  986.      * Large streams (over 2GB) will return a bytes copied value of {@code -1} after the copy has completed since
  987.      * the correct number of bytes cannot be returned as an int. For large streams use the
  988.      * {@link #copyLarge(InputStream, OutputStream)} method.
  989.      * </p>
  990.      *
  991.      * @param inputStream the {@link InputStream} to read.
  992.      * @param outputStream the {@link OutputStream} to write.
  993.      * @return the number of bytes copied, or -1 if greater than {@link Integer#MAX_VALUE}.
  994.      * @throws NullPointerException if the InputStream is {@code null}.
  995.      * @throws NullPointerException if the OutputStream is {@code null}.
  996.      * @throws IOException if an I/O error occurs.
  997.      * @since 1.1
  998.      */
  999.     public static int copy(final InputStream inputStream, final OutputStream outputStream) throws IOException {
  1000.         final long count = copyLarge(inputStream, outputStream);
  1001.         return count > Integer.MAX_VALUE ? EOF : (int) count;
  1002.     }

  1003.     /**
  1004.      * Copies bytes from an {@link InputStream} to an {@link OutputStream} using an internal buffer of the
  1005.      * given size.
  1006.      * <p>
  1007.      * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
  1008.      * </p>
  1009.      *
  1010.      * @param inputStream the {@link InputStream} to read.
  1011.      * @param outputStream the {@link OutputStream} to write to
  1012.      * @param bufferSize the bufferSize used to copy from the input to the output
  1013.      * @return the number of bytes copied.
  1014.      * @throws NullPointerException if the InputStream is {@code null}.
  1015.      * @throws NullPointerException if the OutputStream is {@code null}.
  1016.      * @throws IOException if an I/O error occurs.
  1017.      * @since 2.5
  1018.      */
  1019.     public static long copy(final InputStream inputStream, final OutputStream outputStream, final int bufferSize)
  1020.             throws IOException {
  1021.         return copyLarge(inputStream, outputStream, byteArray(bufferSize));
  1022.     }

  1023.     /**
  1024.      * Copies bytes from an {@link InputStream} to chars on a
  1025.      * {@link Writer} using the virtual machine's {@link Charset#defaultCharset() default charset}.
  1026.      * <p>
  1027.      * This method buffers the input internally, so there is no need to use a
  1028.      * {@link BufferedInputStream}.
  1029.      * </p>
  1030.      * <p>
  1031.      * This method uses {@link InputStreamReader}.
  1032.      * </p>
  1033.      *
  1034.      * @param input the {@link InputStream} to read
  1035.      * @param writer the {@link Writer} to write to
  1036.      * @throws NullPointerException if the input or output is null
  1037.      * @throws IOException          if an I/O error occurs
  1038.      * @since 1.1
  1039.      * @deprecated Use {@link #copy(InputStream, Writer, Charset)} instead
  1040.      */
  1041.     @Deprecated
  1042.     public static void copy(final InputStream input, final Writer writer)
  1043.             throws IOException {
  1044.         copy(input, writer, Charset.defaultCharset());
  1045.     }

  1046.     /**
  1047.      * Copies bytes from an {@link InputStream} to chars on a
  1048.      * {@link Writer} using the specified character encoding.
  1049.      * <p>
  1050.      * This method buffers the input internally, so there is no need to use a
  1051.      * {@link BufferedInputStream}.
  1052.      * </p>
  1053.      * <p>
  1054.      * This method uses {@link InputStreamReader}.
  1055.      * </p>
  1056.      *
  1057.      * @param input the {@link InputStream} to read
  1058.      * @param writer the {@link Writer} to write to
  1059.      * @param inputCharset the charset to use for the input stream, null means platform default
  1060.      * @throws NullPointerException if the input or output is null
  1061.      * @throws IOException          if an I/O error occurs
  1062.      * @since 2.3
  1063.      */
  1064.     public static void copy(final InputStream input, final Writer writer, final Charset inputCharset)
  1065.             throws IOException {
  1066.         copy(new InputStreamReader(input, Charsets.toCharset(inputCharset)), writer);
  1067.     }

  1068.     /**
  1069.      * Copies bytes from an {@link InputStream} to chars on a
  1070.      * {@link Writer} using the specified character encoding.
  1071.      * <p>
  1072.      * This method buffers the input internally, so there is no need to use a
  1073.      * {@link BufferedInputStream}.
  1074.      * </p>
  1075.      * <p>
  1076.      * Character encoding names can be found at
  1077.      * <a href="https://www.iana.org/assignments/character-sets">IANA</a>.
  1078.      * </p>
  1079.      * <p>
  1080.      * This method uses {@link InputStreamReader}.
  1081.      * </p>
  1082.      *
  1083.      * @param input the {@link InputStream} to read
  1084.      * @param writer the {@link Writer} to write to
  1085.      * @param inputCharsetName the name of the requested charset for the InputStream, null means platform default
  1086.      * @throws NullPointerException                         if the input or output is null
  1087.      * @throws IOException                                  if an I/O error occurs
  1088.      * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported
  1089.      * @since 1.1
  1090.      */
  1091.     public static void copy(final InputStream input, final Writer writer, final String inputCharsetName)
  1092.             throws IOException {
  1093.         copy(input, writer, Charsets.toCharset(inputCharsetName));
  1094.     }

  1095.     /**
  1096.      * Copies bytes from a {@link ByteArrayOutputStream} to a {@link QueueInputStream}.
  1097.      * <p>
  1098.      * Unlike using JDK {@link PipedInputStream} and {@link PipedOutputStream} for this, this
  1099.      * solution works safely in a single thread environment.
  1100.      * </p>
  1101.      * <p>
  1102.      * Example usage:
  1103.      * </p>
  1104.      *
  1105.      * <pre>
  1106.      * ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  1107.      * outputStream.writeBytes("hello world".getBytes(StandardCharsets.UTF_8));
  1108.      *
  1109.      * InputStream inputStream = IOUtils.copy(outputStream);
  1110.      * </pre>
  1111.      *
  1112.      * @param outputStream the {@link ByteArrayOutputStream} to read.
  1113.      * @return the {@link QueueInputStream} filled with the content of the outputStream.
  1114.      * @throws NullPointerException if the {@link ByteArrayOutputStream} is {@code null}.
  1115.      * @throws IOException if an I/O error occurs.
  1116.      * @since 2.12
  1117.      */
  1118.     @SuppressWarnings("resource") // streams are closed by the caller.
  1119.     public static QueueInputStream copy(final java.io.ByteArrayOutputStream outputStream) throws IOException {
  1120.         Objects.requireNonNull(outputStream, "outputStream");
  1121.         final QueueInputStream in = new QueueInputStream();
  1122.         outputStream.writeTo(in.newQueueOutputStream());
  1123.         return in;
  1124.     }

  1125.     /**
  1126.      * Copies chars from a {@link Reader} to a {@link Appendable}.
  1127.      * <p>
  1128.      * This method buffers the input internally, so there is no need to use a
  1129.      * {@link BufferedReader}.
  1130.      * </p>
  1131.      * <p>
  1132.      * Large streams (over 2GB) will return a chars copied value of
  1133.      * {@code -1} after the copy has completed since the correct
  1134.      * number of chars cannot be returned as an int. For large streams
  1135.      * use the {@link #copyLarge(Reader, Writer)} method.
  1136.      * </p>
  1137.      *
  1138.      * @param reader the {@link Reader} to read
  1139.      * @param output the {@link Appendable} to write to
  1140.      * @return the number of characters copied, or -1 if &gt; Integer.MAX_VALUE
  1141.      * @throws NullPointerException if the input or output is null
  1142.      * @throws IOException          if an I/O error occurs
  1143.      * @since 2.7
  1144.      */
  1145.     public static long copy(final Reader reader, final Appendable output) throws IOException {
  1146.         return copy(reader, output, CharBuffer.allocate(DEFAULT_BUFFER_SIZE));
  1147.     }

  1148.     /**
  1149.      * Copies chars from a {@link Reader} to an {@link Appendable}.
  1150.      * <p>
  1151.      * This method uses the provided buffer, so there is no need to use a
  1152.      * {@link BufferedReader}.
  1153.      * </p>
  1154.      *
  1155.      * @param reader the {@link Reader} to read
  1156.      * @param output the {@link Appendable} to write to
  1157.      * @param buffer the buffer to be used for the copy
  1158.      * @return the number of characters copied
  1159.      * @throws NullPointerException if the input or output is null
  1160.      * @throws IOException          if an I/O error occurs
  1161.      * @since 2.7
  1162.      */
  1163.     public static long copy(final Reader reader, final Appendable output, final CharBuffer buffer) throws IOException {
  1164.         long count = 0;
  1165.         int n;
  1166.         while (EOF != (n = reader.read(buffer))) {
  1167.             buffer.flip();
  1168.             output.append(buffer, 0, n);
  1169.             count += n;
  1170.         }
  1171.         return count;
  1172.     }

  1173.     /**
  1174.      * Copies chars from a {@link Reader} to bytes on an
  1175.      * {@link OutputStream} using the the virtual machine's {@link Charset#defaultCharset() default charset},
  1176.      * and calling flush.
  1177.      * <p>
  1178.      * This method buffers the input internally, so there is no need to use a
  1179.      * {@link BufferedReader}.
  1180.      * </p>
  1181.      * <p>
  1182.      * Due to the implementation of OutputStreamWriter, this method performs a
  1183.      * flush.
  1184.      * </p>
  1185.      * <p>
  1186.      * This method uses {@link OutputStreamWriter}.
  1187.      * </p>
  1188.      *
  1189.      * @param reader the {@link Reader} to read
  1190.      * @param output the {@link OutputStream} to write to
  1191.      * @throws NullPointerException if the input or output is null
  1192.      * @throws IOException          if an I/O error occurs
  1193.      * @since 1.1
  1194.      * @deprecated Use {@link #copy(Reader, OutputStream, Charset)} instead
  1195.      */
  1196.     @Deprecated
  1197.     public static void copy(final Reader reader, final OutputStream output)
  1198.             throws IOException {
  1199.         copy(reader, output, Charset.defaultCharset());
  1200.     }

  1201.     /**
  1202.      * Copies chars from a {@link Reader} to bytes on an
  1203.      * {@link OutputStream} using the specified character encoding, and
  1204.      * calling flush.
  1205.      * <p>
  1206.      * This method buffers the input internally, so there is no need to use a
  1207.      * {@link BufferedReader}.
  1208.      * </p>
  1209.      * <p>
  1210.      * Due to the implementation of OutputStreamWriter, this method performs a
  1211.      * flush.
  1212.      * </p>
  1213.      * <p>
  1214.      * This method uses {@link OutputStreamWriter}.
  1215.      * </p>
  1216.      *
  1217.      * @param reader the {@link Reader} to read
  1218.      * @param output the {@link OutputStream} to write to
  1219.      * @param outputCharset the charset to use for the OutputStream, null means platform default
  1220.      * @throws NullPointerException if the input or output is null
  1221.      * @throws IOException          if an I/O error occurs
  1222.      * @since 2.3
  1223.      */
  1224.     public static void copy(final Reader reader, final OutputStream output, final Charset outputCharset)
  1225.             throws IOException {
  1226.         final OutputStreamWriter writer = new OutputStreamWriter(output, Charsets.toCharset(outputCharset));
  1227.         copy(reader, writer);
  1228.         // XXX Unless anyone is planning on rewriting OutputStreamWriter,
  1229.         // we have to flush here.
  1230.         writer.flush();
  1231.     }

  1232.     /**
  1233.      * Copies chars from a {@link Reader} to bytes on an
  1234.      * {@link OutputStream} using the specified character encoding, and
  1235.      * calling flush.
  1236.      * <p>
  1237.      * This method buffers the input internally, so there is no need to use a
  1238.      * {@link BufferedReader}.
  1239.      * </p>
  1240.      * <p>
  1241.      * Character encoding names can be found at
  1242.      * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
  1243.      * </p>
  1244.      * <p>
  1245.      * Due to the implementation of OutputStreamWriter, this method performs a
  1246.      * flush.
  1247.      * </p>
  1248.      * <p>
  1249.      * This method uses {@link OutputStreamWriter}.
  1250.      * </p>
  1251.      *
  1252.      * @param reader the {@link Reader} to read
  1253.      * @param output the {@link OutputStream} to write to
  1254.      * @param outputCharsetName the name of the requested charset for the OutputStream, null means platform default
  1255.      * @throws NullPointerException                         if the input or output is null
  1256.      * @throws IOException                                  if an I/O error occurs
  1257.      * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported
  1258.      * @since 1.1
  1259.      */
  1260.     public static void copy(final Reader reader, final OutputStream output, final String outputCharsetName)
  1261.             throws IOException {
  1262.         copy(reader, output, Charsets.toCharset(outputCharsetName));
  1263.     }

  1264.     /**
  1265.      * Copies chars from a {@link Reader} to a {@link Writer}.
  1266.      * <p>
  1267.      * This method buffers the input internally, so there is no need to use a
  1268.      * {@link BufferedReader}.
  1269.      * </p>
  1270.      * <p>
  1271.      * Large streams (over 2GB) will return a chars copied value of
  1272.      * {@code -1} after the copy has completed since the correct
  1273.      * number of chars cannot be returned as an int. For large streams
  1274.      * use the {@link #copyLarge(Reader, Writer)} method.
  1275.      * </p>
  1276.      *
  1277.      * @param reader the {@link Reader} to read.
  1278.      * @param writer the {@link Writer} to write.
  1279.      * @return the number of characters copied, or -1 if &gt; Integer.MAX_VALUE
  1280.      * @throws NullPointerException if the input or output is null
  1281.      * @throws IOException          if an I/O error occurs
  1282.      * @since 1.1
  1283.      */
  1284.     public static int copy(final Reader reader, final Writer writer) throws IOException {
  1285.         final long count = copyLarge(reader, writer);
  1286.         if (count > Integer.MAX_VALUE) {
  1287.             return EOF;
  1288.         }
  1289.         return (int) count;
  1290.     }

  1291.     /**
  1292.      * Copies bytes from a {@link URL} to an {@link OutputStream}.
  1293.      * <p>
  1294.      * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
  1295.      * </p>
  1296.      * <p>
  1297.      * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
  1298.      * </p>
  1299.      *
  1300.      * @param url the {@link URL} to read.
  1301.      * @param file the {@link OutputStream} to write.
  1302.      * @return the number of bytes copied.
  1303.      * @throws NullPointerException if the URL is {@code null}.
  1304.      * @throws NullPointerException if the OutputStream is {@code null}.
  1305.      * @throws IOException if an I/O error occurs.
  1306.      * @since 2.9.0
  1307.      */
  1308.     public static long copy(final URL url, final File file) throws IOException {
  1309.         try (OutputStream outputStream = Files.newOutputStream(Objects.requireNonNull(file, "file").toPath())) {
  1310.             return copy(url, outputStream);
  1311.         }
  1312.     }

  1313.     /**
  1314.      * Copies bytes from a {@link URL} to an {@link OutputStream}.
  1315.      * <p>
  1316.      * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
  1317.      * </p>
  1318.      * <p>
  1319.      * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
  1320.      * </p>
  1321.      *
  1322.      * @param url the {@link URL} to read.
  1323.      * @param outputStream the {@link OutputStream} to write.
  1324.      * @return the number of bytes copied.
  1325.      * @throws NullPointerException if the URL is {@code null}.
  1326.      * @throws NullPointerException if the OutputStream is {@code null}.
  1327.      * @throws IOException if an I/O error occurs.
  1328.      * @since 2.9.0
  1329.      */
  1330.     public static long copy(final URL url, final OutputStream outputStream) throws IOException {
  1331.         try (InputStream inputStream = Objects.requireNonNull(url, "url").openStream()) {
  1332.             return copyLarge(inputStream, outputStream);
  1333.         }
  1334.     }

  1335.     /**
  1336.      * Copies bytes from a large (over 2GB) {@link InputStream} to an
  1337.      * {@link OutputStream}.
  1338.      * <p>
  1339.      * This method buffers the input internally, so there is no need to use a
  1340.      * {@link BufferedInputStream}.
  1341.      * </p>
  1342.      * <p>
  1343.      * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
  1344.      * </p>
  1345.      *
  1346.      * @param inputStream the {@link InputStream} to read.
  1347.      * @param outputStream the {@link OutputStream} to write.
  1348.      * @return the number of bytes copied.
  1349.      * @throws NullPointerException if the InputStream is {@code null}.
  1350.      * @throws NullPointerException if the OutputStream is {@code null}.
  1351.      * @throws IOException if an I/O error occurs.
  1352.      * @since 1.3
  1353.      */
  1354.     public static long copyLarge(final InputStream inputStream, final OutputStream outputStream)
  1355.             throws IOException {
  1356.         return copy(inputStream, outputStream, DEFAULT_BUFFER_SIZE);
  1357.     }

  1358.     /**
  1359.      * Copies bytes from a large (over 2GB) {@link InputStream} to an
  1360.      * {@link OutputStream}.
  1361.      * <p>
  1362.      * This method uses the provided buffer, so there is no need to use a
  1363.      * {@link BufferedInputStream}.
  1364.      * </p>
  1365.      *
  1366.      * @param inputStream the {@link InputStream} to read.
  1367.      * @param outputStream the {@link OutputStream} to write.
  1368.      * @param buffer the buffer to use for the copy
  1369.      * @return the number of bytes copied.
  1370.      * @throws NullPointerException if the InputStream is {@code null}.
  1371.      * @throws NullPointerException if the OutputStream is {@code null}.
  1372.      * @throws IOException if an I/O error occurs.
  1373.      * @since 2.2
  1374.      */
  1375.     @SuppressWarnings("resource") // streams are closed by the caller.
  1376.     public static long copyLarge(final InputStream inputStream, final OutputStream outputStream, final byte[] buffer)
  1377.         throws IOException {
  1378.         Objects.requireNonNull(inputStream, "inputStream");
  1379.         Objects.requireNonNull(outputStream, "outputStream");
  1380.         long count = 0;
  1381.         int n;
  1382.         while (EOF != (n = inputStream.read(buffer))) {
  1383.             outputStream.write(buffer, 0, n);
  1384.             count += n;
  1385.         }
  1386.         return count;
  1387.     }

  1388.     /**
  1389.      * Copies some or all bytes from a large (over 2GB) {@link InputStream} to an
  1390.      * {@link OutputStream}, optionally skipping input bytes.
  1391.      * <p>
  1392.      * This method buffers the input internally, so there is no need to use a
  1393.      * {@link BufferedInputStream}.
  1394.      * </p>
  1395.      * <p>
  1396.      * Note that the implementation uses {@link #skip(InputStream, long)}.
  1397.      * This means that the method may be considerably less efficient than using the actual skip implementation,
  1398.      * this is done to guarantee that the correct number of characters are skipped.
  1399.      * </p>
  1400.      * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
  1401.      *
  1402.      * @param input the {@link InputStream} to read.
  1403.      * @param output the {@link OutputStream} to write.
  1404.      * @param inputOffset number of bytes to skip from input before copying, these bytes are ignored.
  1405.      * @param length number of bytes to copy.
  1406.      * @return the number of bytes copied.
  1407.      * @throws NullPointerException if the input or output is null.
  1408.      * @throws IOException          if an I/O error occurs.
  1409.      * @since 2.2
  1410.      */
  1411.     public static long copyLarge(final InputStream input, final OutputStream output, final long inputOffset,
  1412.                                  final long length) throws IOException {
  1413.         return copyLarge(input, output, inputOffset, length, getScratchByteArray());
  1414.     }

  1415.     /**
  1416.      * Copies some or all bytes from a large (over 2GB) {@link InputStream} to an
  1417.      * {@link OutputStream}, optionally skipping input bytes.
  1418.      * <p>
  1419.      * This method uses the provided buffer, so there is no need to use a
  1420.      * {@link BufferedInputStream}.
  1421.      * </p>
  1422.      * <p>
  1423.      * Note that the implementation uses {@link #skip(InputStream, long)}.
  1424.      * This means that the method may be considerably less efficient than using the actual skip implementation,
  1425.      * this is done to guarantee that the correct number of characters are skipped.
  1426.      * </p>
  1427.      *
  1428.      * @param input the {@link InputStream} to read.
  1429.      * @param output the {@link OutputStream} to write.
  1430.      * @param inputOffset number of bytes to skip from input before copying, these bytes are ignored.
  1431.      * @param length number of bytes to copy.
  1432.      * @param buffer the buffer to use for the copy.
  1433.      * @return the number of bytes copied.
  1434.      * @throws NullPointerException if the input or output is null.
  1435.      * @throws IOException          if an I/O error occurs.
  1436.      * @since 2.2
  1437.      */
  1438.     public static long copyLarge(final InputStream input, final OutputStream output,
  1439.                                  final long inputOffset, final long length, final byte[] buffer) throws IOException {
  1440.         if (inputOffset > 0) {
  1441.             skipFully(input, inputOffset);
  1442.         }
  1443.         if (length == 0) {
  1444.             return 0;
  1445.         }
  1446.         final int bufferLength = buffer.length;
  1447.         int bytesToRead = bufferLength;
  1448.         if (length > 0 && length < bufferLength) {
  1449.             bytesToRead = (int) length;
  1450.         }
  1451.         int read;
  1452.         long totalRead = 0;
  1453.         while (bytesToRead > 0 && EOF != (read = input.read(buffer, 0, bytesToRead))) {
  1454.             output.write(buffer, 0, read);
  1455.             totalRead += read;
  1456.             if (length > 0) { // only adjust length if not reading to the end
  1457.                 // Note the cast must work because buffer.length is an integer
  1458.                 bytesToRead = (int) Math.min(length - totalRead, bufferLength);
  1459.             }
  1460.         }
  1461.         return totalRead;
  1462.     }

  1463.     /**
  1464.      * Copies chars from a large (over 2GB) {@link Reader} to a {@link Writer}.
  1465.      * <p>
  1466.      * This method buffers the input internally, so there is no need to use a
  1467.      * {@link BufferedReader}.
  1468.      * </p>
  1469.      * <p>
  1470.      * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
  1471.      * </p>
  1472.      *
  1473.      * @param reader the {@link Reader} to source.
  1474.      * @param writer the {@link Writer} to target.
  1475.      * @return the number of characters copied
  1476.      * @throws NullPointerException if the input or output is null
  1477.      * @throws IOException          if an I/O error occurs
  1478.      * @since 1.3
  1479.      */
  1480.     public static long copyLarge(final Reader reader, final Writer writer) throws IOException {
  1481.         return copyLarge(reader, writer, getScratchCharArray());
  1482.     }

  1483.     /**
  1484.      * Copies chars from a large (over 2GB) {@link Reader} to a {@link Writer}.
  1485.      * <p>
  1486.      * This method uses the provided buffer, so there is no need to use a
  1487.      * {@link BufferedReader}.
  1488.      * </p>
  1489.      *
  1490.      * @param reader the {@link Reader} to source.
  1491.      * @param writer the {@link Writer} to target.
  1492.      * @param buffer the buffer to be used for the copy
  1493.      * @return the number of characters copied
  1494.      * @throws NullPointerException if the input or output is null
  1495.      * @throws IOException          if an I/O error occurs
  1496.      * @since 2.2
  1497.      */
  1498.     public static long copyLarge(final Reader reader, final Writer writer, final char[] buffer) throws IOException {
  1499.         long count = 0;
  1500.         int n;
  1501.         while (EOF != (n = reader.read(buffer))) {
  1502.             writer.write(buffer, 0, n);
  1503.             count += n;
  1504.         }
  1505.         return count;
  1506.     }

  1507.     /**
  1508.      * Copies some or all chars from a large (over 2GB) {@link InputStream} to an
  1509.      * {@link OutputStream}, optionally skipping input chars.
  1510.      * <p>
  1511.      * This method buffers the input internally, so there is no need to use a
  1512.      * {@link BufferedReader}.
  1513.      * </p>
  1514.      * <p>
  1515.      * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
  1516.      * </p>
  1517.      *
  1518.      * @param reader the {@link Reader} to read
  1519.      * @param writer the {@link Writer} to write to
  1520.      * @param inputOffset number of chars to skip from input before copying
  1521.      * -ve values are ignored
  1522.      * @param length number of chars to copy. -ve means all
  1523.      * @return the number of chars copied
  1524.      * @throws NullPointerException if the input or output is null
  1525.      * @throws IOException          if an I/O error occurs
  1526.      * @since 2.2
  1527.      */
  1528.     public static long copyLarge(final Reader reader, final Writer writer, final long inputOffset, final long length)
  1529.             throws IOException {
  1530.         return copyLarge(reader, writer, inputOffset, length, getScratchCharArray());
  1531.     }

  1532.     /**
  1533.      * Copies some or all chars from a large (over 2GB) {@link InputStream} to an
  1534.      * {@link OutputStream}, optionally skipping input chars.
  1535.      * <p>
  1536.      * This method uses the provided buffer, so there is no need to use a
  1537.      * {@link BufferedReader}.
  1538.      * </p>
  1539.      *
  1540.      * @param reader the {@link Reader} to read
  1541.      * @param writer the {@link Writer} to write to
  1542.      * @param inputOffset number of chars to skip from input before copying
  1543.      * -ve values are ignored
  1544.      * @param length number of chars to copy. -ve means all
  1545.      * @param buffer the buffer to be used for the copy
  1546.      * @return the number of chars copied
  1547.      * @throws NullPointerException if the input or output is null
  1548.      * @throws IOException          if an I/O error occurs
  1549.      * @since 2.2
  1550.      */
  1551.     public static long copyLarge(final Reader reader, final Writer writer, final long inputOffset, final long length,
  1552.                                  final char[] buffer)
  1553.             throws IOException {
  1554.         if (inputOffset > 0) {
  1555.             skipFully(reader, inputOffset);
  1556.         }
  1557.         if (length == 0) {
  1558.             return 0;
  1559.         }
  1560.         int bytesToRead = buffer.length;
  1561.         if (length > 0 && length < buffer.length) {
  1562.             bytesToRead = (int) length;
  1563.         }
  1564.         int read;
  1565.         long totalRead = 0;
  1566.         while (bytesToRead > 0 && EOF != (read = reader.read(buffer, 0, bytesToRead))) {
  1567.             writer.write(buffer, 0, read);
  1568.             totalRead += read;
  1569.             if (length > 0) { // only adjust length if not reading to the end
  1570.                 // Note the cast must work because buffer.length is an integer
  1571.                 bytesToRead = (int) Math.min(length - totalRead, buffer.length);
  1572.             }
  1573.         }
  1574.         return totalRead;
  1575.     }

  1576.     /**
  1577.      * Fills the given array with 0s.
  1578.      *
  1579.      * @param arr The non-null array to fill.
  1580.      * @return The given array.
  1581.      */
  1582.     private static byte[] fill0(final byte[] arr) {
  1583.         Arrays.fill(arr, (byte) 0);
  1584.         return arr;
  1585.     }

  1586.     /**
  1587.      * Fills the given array with 0s.
  1588.      *
  1589.      * @param arr The non-null array to fill.
  1590.      * @return The given array.
  1591.      */
  1592.     private static char[] fill0(final char[] arr) {
  1593.         Arrays.fill(arr, (char) 0);
  1594.         return arr;
  1595.     }

  1596.     /**
  1597.      * Gets the internal byte array buffer, intended for both reading and writing.
  1598.      *
  1599.      * @return the internal byte array buffer, intended for both reading and writing.
  1600.      */
  1601.     static byte[] getScratchByteArray() {
  1602.         return fill0(SCRATCH_BYTE_BUFFER_RW.get());
  1603.     }

  1604.     /**
  1605.      * Gets the internal byte array intended for write only operations.
  1606.      *
  1607.      * @return the internal byte array intended for write only operations.
  1608.      */
  1609.     static byte[] getScratchByteArrayWriteOnly() {
  1610.         return fill0(SCRATCH_BYTE_BUFFER_WO);
  1611.     }

  1612.     /**
  1613.      * Gets the char byte array buffer, intended for both reading and writing.
  1614.      *
  1615.      * @return the char byte array buffer, intended for both reading and writing.
  1616.      */
  1617.     static char[] getScratchCharArray() {
  1618.         return fill0(SCRATCH_CHAR_BUFFER_RW.get());
  1619.     }

  1620.     /**
  1621.      * Gets the internal char array intended for write only operations.
  1622.      *
  1623.      * @return the internal char array intended for write only operations.
  1624.      */
  1625.     static char[] getScratchCharArrayWriteOnly() {
  1626.         return fill0(SCRATCH_CHAR_BUFFER_WO);
  1627.     }

  1628.     /**
  1629.      * Returns the length of the given array in a null-safe manner.
  1630.      *
  1631.      * @param array an array or null
  1632.      * @return the array length, or 0 if the given array is null.
  1633.      * @since 2.7
  1634.      */
  1635.     public static int length(final byte[] array) {
  1636.         return array == null ? 0 : array.length;
  1637.     }

  1638.     /**
  1639.      * Returns the length of the given array in a null-safe manner.
  1640.      *
  1641.      * @param array an array or null
  1642.      * @return the array length, or 0 if the given array is null.
  1643.      * @since 2.7
  1644.      */
  1645.     public static int length(final char[] array) {
  1646.         return array == null ? 0 : array.length;
  1647.     }

  1648.     /**
  1649.      * Returns the length of the given CharSequence in a null-safe manner.
  1650.      *
  1651.      * @param csq a CharSequence or null
  1652.      * @return the CharSequence length, or 0 if the given CharSequence is null.
  1653.      * @since 2.7
  1654.      */
  1655.     public static int length(final CharSequence csq) {
  1656.         return csq == null ? 0 : csq.length();
  1657.     }

  1658.     /**
  1659.      * Returns the length of the given array in a null-safe manner.
  1660.      *
  1661.      * @param array an array or null
  1662.      * @return the array length, or 0 if the given array is null.
  1663.      * @since 2.7
  1664.      */
  1665.     public static int length(final Object[] array) {
  1666.         return array == null ? 0 : array.length;
  1667.     }

  1668.     /**
  1669.      * Returns an Iterator for the lines in an {@link InputStream}, using
  1670.      * the character encoding specified (or default encoding if null).
  1671.      * <p>
  1672.      * {@link LineIterator} holds a reference to the open
  1673.      * {@link InputStream} specified here. When you have finished with
  1674.      * the iterator you should close the stream to free internal resources.
  1675.      * This can be done by using a try-with-resources block, closing the stream directly, or by calling
  1676.      * {@link LineIterator#close()}.
  1677.      * </p>
  1678.      * <p>
  1679.      * The recommended usage pattern is:
  1680.      * </p>
  1681.      * <pre>
  1682.      * try {
  1683.      *   LineIterator it = IOUtils.lineIterator(stream, charset);
  1684.      *   while (it.hasNext()) {
  1685.      *     String line = it.nextLine();
  1686.      *     /// do something with line
  1687.      *   }
  1688.      * } finally {
  1689.      *   IOUtils.closeQuietly(stream);
  1690.      * }
  1691.      * </pre>
  1692.      *
  1693.      * @param input the {@link InputStream} to read, not null
  1694.      * @param charset the charset to use, null means platform default
  1695.      * @return an Iterator of the lines in the reader, never null
  1696.      * @throws IllegalArgumentException if the input is null
  1697.      * @since 2.3
  1698.      */
  1699.     public static LineIterator lineIterator(final InputStream input, final Charset charset) {
  1700.         return new LineIterator(new InputStreamReader(input, Charsets.toCharset(charset)));
  1701.     }

  1702.     /**
  1703.      * Returns an Iterator for the lines in an {@link InputStream}, using
  1704.      * the character encoding specified (or default encoding if null).
  1705.      * <p>
  1706.      * {@link LineIterator} holds a reference to the open
  1707.      * {@link InputStream} specified here. When you have finished with
  1708.      * the iterator you should close the stream to free internal resources.
  1709.      * This can be done by using a try-with-resources block, closing the stream directly, or by calling
  1710.      * {@link LineIterator#close()}.
  1711.      * </p>
  1712.      * <p>
  1713.      * The recommended usage pattern is:
  1714.      * </p>
  1715.      * <pre>
  1716.      * try {
  1717.      *   LineIterator it = IOUtils.lineIterator(stream, StandardCharsets.UTF_8.name());
  1718.      *   while (it.hasNext()) {
  1719.      *     String line = it.nextLine();
  1720.      *     /// do something with line
  1721.      *   }
  1722.      * } finally {
  1723.      *   IOUtils.closeQuietly(stream);
  1724.      * }
  1725.      * </pre>
  1726.      *
  1727.      * @param input the {@link InputStream} to read, not null
  1728.      * @param charsetName the encoding to use, null means platform default
  1729.      * @return an Iterator of the lines in the reader, never null
  1730.      * @throws IllegalArgumentException                     if the input is null
  1731.      * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported
  1732.      * @since 1.2
  1733.      */
  1734.     public static LineIterator lineIterator(final InputStream input, final String charsetName) {
  1735.         return lineIterator(input, Charsets.toCharset(charsetName));
  1736.     }

  1737.     /**
  1738.      * Returns an Iterator for the lines in a {@link Reader}.
  1739.      * <p>
  1740.      * {@link LineIterator} holds a reference to the open
  1741.      * {@link Reader} specified here. When you have finished with the
  1742.      * iterator you should close the reader to free internal resources.
  1743.      * This can be done by using a try-with-resources block, closing the reader directly, or by calling
  1744.      * {@link LineIterator#close()}.
  1745.      * </p>
  1746.      * <p>
  1747.      * The recommended usage pattern is:
  1748.      * </p>
  1749.      * <pre>
  1750.      * try {
  1751.      *   LineIterator it = IOUtils.lineIterator(reader);
  1752.      *   while (it.hasNext()) {
  1753.      *     String line = it.nextLine();
  1754.      *     /// do something with line
  1755.      *   }
  1756.      * } finally {
  1757.      *   IOUtils.closeQuietly(reader);
  1758.      * }
  1759.      * </pre>
  1760.      *
  1761.      * @param reader the {@link Reader} to read, not null
  1762.      * @return an Iterator of the lines in the reader, never null
  1763.      * @throws NullPointerException if the reader is null
  1764.      * @since 1.2
  1765.      */
  1766.     public static LineIterator lineIterator(final Reader reader) {
  1767.         return new LineIterator(reader);
  1768.     }

  1769.     /**
  1770.      * Reads bytes from an input stream.
  1771.      * This implementation guarantees that it will read as many bytes
  1772.      * as possible before giving up; this may not always be the case for
  1773.      * subclasses of {@link InputStream}.
  1774.      *
  1775.      * @param input where to read input from
  1776.      * @param buffer destination
  1777.      * @return actual length read; may be less than requested if EOF was reached
  1778.      * @throws IOException if a read error occurs
  1779.      * @since 2.2
  1780.      */
  1781.     public static int read(final InputStream input, final byte[] buffer) throws IOException {
  1782.         return read(input, buffer, 0, buffer.length);
  1783.     }

  1784.     /**
  1785.      * Reads bytes from an input stream.
  1786.      * This implementation guarantees that it will read as many bytes
  1787.      * as possible before giving up; this may not always be the case for
  1788.      * subclasses of {@link InputStream}.
  1789.      *
  1790.      * @param input where to read input
  1791.      * @param buffer destination
  1792.      * @param offset initial offset into buffer
  1793.      * @param length length to read, must be &gt;= 0
  1794.      * @return actual length read; may be less than requested if EOF was reached
  1795.      * @throws IllegalArgumentException if length is negative
  1796.      * @throws IOException              if a read error occurs
  1797.      * @since 2.2
  1798.      */
  1799.     public static int read(final InputStream input, final byte[] buffer, final int offset, final int length)
  1800.             throws IOException {
  1801.         if (length == 0) {
  1802.             return 0;
  1803.         }
  1804.         return read(input::read, buffer, offset, length);
  1805.     }

  1806.     /**
  1807.      * Reads bytes from an input. This implementation guarantees that it will read as many bytes as possible before giving up; this may not always be the case
  1808.      * for subclasses of {@link InputStream}.
  1809.      *
  1810.      * @param input  How to read input
  1811.      * @param buffer destination
  1812.      * @param offset initial offset into buffer
  1813.      * @param length length to read, must be &gt;= 0
  1814.      * @return actual length read; may be less than requested if EOF was reached
  1815.      * @throws IllegalArgumentException if length is negative
  1816.      * @throws IOException              if a read error occurs
  1817.      * @since 2.2
  1818.      */
  1819.     static int read(final IOTriFunction<byte[], Integer, Integer, Integer> input, final byte[] buffer, final int offset, final int length)
  1820.             throws IOException {
  1821.         if (length < 0) {
  1822.             throw new IllegalArgumentException("Length must not be negative: " + length);
  1823.         }
  1824.         int remaining = length;
  1825.         while (remaining > 0) {
  1826.             final int location = length - remaining;
  1827.             final int count = input.apply(buffer, offset + location, remaining);
  1828.             if (EOF == count) {
  1829.                 break;
  1830.             }
  1831.             remaining -= count;
  1832.         }
  1833.         return length - remaining;
  1834.     }

  1835.     /**
  1836.      * Reads bytes from a ReadableByteChannel.
  1837.      * <p>
  1838.      * This implementation guarantees that it will read as many bytes
  1839.      * as possible before giving up; this may not always be the case for
  1840.      * subclasses of {@link ReadableByteChannel}.
  1841.      * </p>
  1842.      *
  1843.      * @param input the byte channel to read
  1844.      * @param buffer byte buffer destination
  1845.      * @return the actual length read; may be less than requested if EOF was reached
  1846.      * @throws IOException if a read error occurs
  1847.      * @since 2.5
  1848.      */
  1849.     public static int read(final ReadableByteChannel input, final ByteBuffer buffer) throws IOException {
  1850.         final int length = buffer.remaining();
  1851.         while (buffer.remaining() > 0) {
  1852.             final int count = input.read(buffer);
  1853.             if (EOF == count) { // EOF
  1854.                 break;
  1855.             }
  1856.         }
  1857.         return length - buffer.remaining();
  1858.     }

  1859.     /**
  1860.      * Reads characters from an input character stream.
  1861.      * This implementation guarantees that it will read as many characters
  1862.      * as possible before giving up; this may not always be the case for
  1863.      * subclasses of {@link Reader}.
  1864.      *
  1865.      * @param reader where to read input from
  1866.      * @param buffer destination
  1867.      * @return actual length read; may be less than requested if EOF was reached
  1868.      * @throws IOException if a read error occurs
  1869.      * @since 2.2
  1870.      */
  1871.     public static int read(final Reader reader, final char[] buffer) throws IOException {
  1872.         return read(reader, buffer, 0, buffer.length);
  1873.     }

  1874.     /**
  1875.      * Reads characters from an input character stream.
  1876.      * This implementation guarantees that it will read as many characters
  1877.      * as possible before giving up; this may not always be the case for
  1878.      * subclasses of {@link Reader}.
  1879.      *
  1880.      * @param reader where to read input from
  1881.      * @param buffer destination
  1882.      * @param offset initial offset into buffer
  1883.      * @param length length to read, must be &gt;= 0
  1884.      * @return actual length read; may be less than requested if EOF was reached
  1885.      * @throws IllegalArgumentException if length is negative
  1886.      * @throws IOException              if a read error occurs
  1887.      * @since 2.2
  1888.      */
  1889.     public static int read(final Reader reader, final char[] buffer, final int offset, final int length)
  1890.             throws IOException {
  1891.         if (length < 0) {
  1892.             throw new IllegalArgumentException("Length must not be negative: " + length);
  1893.         }
  1894.         int remaining = length;
  1895.         while (remaining > 0) {
  1896.             final int location = length - remaining;
  1897.             final int count = reader.read(buffer, offset + location, remaining);
  1898.             if (EOF == count) { // EOF
  1899.                 break;
  1900.             }
  1901.             remaining -= count;
  1902.         }
  1903.         return length - remaining;
  1904.     }

  1905.     /**
  1906.      * Reads the requested number of bytes or fail if there are not enough left.
  1907.      * <p>
  1908.      * This allows for the possibility that {@link InputStream#read(byte[], int, int)} may
  1909.      * not read as many bytes as requested (most likely because of reaching EOF).
  1910.      * </p>
  1911.      *
  1912.      * @param input where to read input from
  1913.      * @param buffer destination
  1914.      * @throws IOException              if there is a problem reading the file
  1915.      * @throws IllegalArgumentException if length is negative
  1916.      * @throws EOFException             if the number of bytes read was incorrect
  1917.      * @since 2.2
  1918.      */
  1919.     public static void readFully(final InputStream input, final byte[] buffer) throws IOException {
  1920.         readFully(input, buffer, 0, buffer.length);
  1921.     }

  1922.     /**
  1923.      * Reads the requested number of bytes or fail if there are not enough left.
  1924.      * <p>
  1925.      * This allows for the possibility that {@link InputStream#read(byte[], int, int)} may
  1926.      * not read as many bytes as requested (most likely because of reaching EOF).
  1927.      * </p>
  1928.      *
  1929.      * @param input where to read input from
  1930.      * @param buffer destination
  1931.      * @param offset initial offset into buffer
  1932.      * @param length length to read, must be &gt;= 0
  1933.      * @throws IOException              if there is a problem reading the file
  1934.      * @throws IllegalArgumentException if length is negative
  1935.      * @throws EOFException             if the number of bytes read was incorrect
  1936.      * @since 2.2
  1937.      */
  1938.     public static void readFully(final InputStream input, final byte[] buffer, final int offset, final int length)
  1939.             throws IOException {
  1940.         final int actual = read(input, buffer, offset, length);
  1941.         if (actual != length) {
  1942.             throw new EOFException("Length to read: " + length + " actual: " + actual);
  1943.         }
  1944.     }

  1945.     /**
  1946.      * Reads the requested number of bytes or fail if there are not enough left.
  1947.      * <p>
  1948.      * This allows for the possibility that {@link InputStream#read(byte[], int, int)} may
  1949.      * not read as many bytes as requested (most likely because of reaching EOF).
  1950.      * </p>
  1951.      *
  1952.      * @param input where to read input from
  1953.      * @param length length to read, must be &gt;= 0
  1954.      * @return the bytes read from input
  1955.      * @throws IOException              if there is a problem reading the file
  1956.      * @throws IllegalArgumentException if length is negative
  1957.      * @throws EOFException             if the number of bytes read was incorrect
  1958.      * @since 2.5
  1959.      */
  1960.     public static byte[] readFully(final InputStream input, final int length) throws IOException {
  1961.         final byte[] buffer = byteArray(length);
  1962.         readFully(input, buffer, 0, buffer.length);
  1963.         return buffer;
  1964.     }

  1965.     /**
  1966.      * Reads the requested number of bytes or fail if there are not enough left.
  1967.      * <p>
  1968.      * This allows for the possibility that {@link ReadableByteChannel#read(ByteBuffer)} may
  1969.      * not read as many bytes as requested (most likely because of reaching EOF).
  1970.      * </p>
  1971.      *
  1972.      * @param input the byte channel to read
  1973.      * @param buffer byte buffer destination
  1974.      * @throws IOException  if there is a problem reading the file
  1975.      * @throws EOFException if the number of bytes read was incorrect
  1976.      * @since 2.5
  1977.      */
  1978.     public static void readFully(final ReadableByteChannel input, final ByteBuffer buffer) throws IOException {
  1979.         final int expected = buffer.remaining();
  1980.         final int actual = read(input, buffer);
  1981.         if (actual != expected) {
  1982.             throw new EOFException("Length to read: " + expected + " actual: " + actual);
  1983.         }
  1984.     }

  1985.     /**
  1986.      * Reads the requested number of characters or fail if there are not enough left.
  1987.      * <p>
  1988.      * This allows for the possibility that {@link Reader#read(char[], int, int)} may
  1989.      * not read as many characters as requested (most likely because of reaching EOF).
  1990.      * </p>
  1991.      *
  1992.      * @param reader where to read input from
  1993.      * @param buffer destination
  1994.      * @throws IOException              if there is a problem reading the file
  1995.      * @throws IllegalArgumentException if length is negative
  1996.      * @throws EOFException             if the number of characters read was incorrect
  1997.      * @since 2.2
  1998.      */
  1999.     public static void readFully(final Reader reader, final char[] buffer) throws IOException {
  2000.         readFully(reader, buffer, 0, buffer.length);
  2001.     }

  2002.     /**
  2003.      * Reads the requested number of characters or fail if there are not enough left.
  2004.      * <p>
  2005.      * This allows for the possibility that {@link Reader#read(char[], int, int)} may
  2006.      * not read as many characters as requested (most likely because of reaching EOF).
  2007.      * </p>
  2008.      *
  2009.      * @param reader where to read input from
  2010.      * @param buffer destination
  2011.      * @param offset initial offset into buffer
  2012.      * @param length length to read, must be &gt;= 0
  2013.      * @throws IOException              if there is a problem reading the file
  2014.      * @throws IllegalArgumentException if length is negative
  2015.      * @throws EOFException             if the number of characters read was incorrect
  2016.      * @since 2.2
  2017.      */
  2018.     public static void readFully(final Reader reader, final char[] buffer, final int offset, final int length)
  2019.             throws IOException {
  2020.         final int actual = read(reader, buffer, offset, length);
  2021.         if (actual != length) {
  2022.             throw new EOFException("Length to read: " + length + " actual: " + actual);
  2023.         }
  2024.     }

  2025.     /**
  2026.      * Gets the contents of a {@link CharSequence} as a list of Strings, one entry per line.
  2027.      *
  2028.      * @param csq the {@link CharSequence} to read, not null
  2029.      * @return the list of Strings, never null
  2030.      * @throws UncheckedIOException if an I/O error occurs
  2031.      * @since 2.18.0
  2032.      */
  2033.     public static List<String> readLines(final CharSequence csq) throws UncheckedIOException {
  2034.         try (CharSequenceReader reader = new CharSequenceReader(csq)) {
  2035.             return readLines(reader);
  2036.         }
  2037.     }

  2038.     /**
  2039.      * Gets the contents of an {@link InputStream} as a list of Strings,
  2040.      * one entry per line, using the virtual machine's {@link Charset#defaultCharset() default charset}.
  2041.      * <p>
  2042.      * This method buffers the input internally, so there is no need to use a
  2043.      * {@link BufferedInputStream}.
  2044.      * </p>
  2045.      *
  2046.      * @param input the {@link InputStream} to read, not null
  2047.      * @return the list of Strings, never null
  2048.      * @throws NullPointerException if the input is null
  2049.      * @throws UncheckedIOException if an I/O error occurs
  2050.      * @since 1.1
  2051.      * @deprecated Use {@link #readLines(InputStream, Charset)} instead
  2052.      */
  2053.     @Deprecated
  2054.     public static List<String> readLines(final InputStream input) throws UncheckedIOException {
  2055.         return readLines(input, Charset.defaultCharset());
  2056.     }

  2057.     /**
  2058.      * Gets the contents of an {@link InputStream} as a list of Strings,
  2059.      * one entry per line, using the specified character encoding.
  2060.      * <p>
  2061.      * This method buffers the input internally, so there is no need to use a
  2062.      * {@link BufferedInputStream}.
  2063.      * </p>
  2064.      *
  2065.      * @param input the {@link InputStream} to read, not null
  2066.      * @param charset the charset to use, null means platform default
  2067.      * @return the list of Strings, never null
  2068.      * @throws NullPointerException if the input is null
  2069.      * @throws UncheckedIOException if an I/O error occurs
  2070.      * @since 2.3
  2071.      */
  2072.     public static List<String> readLines(final InputStream input, final Charset charset) throws UncheckedIOException {
  2073.         return readLines(new InputStreamReader(input, Charsets.toCharset(charset)));
  2074.     }

  2075.     /**
  2076.      * Gets the contents of an {@link InputStream} as a list of Strings,
  2077.      * one entry per line, using the specified character encoding.
  2078.      * <p>
  2079.      * Character encoding names can be found at
  2080.      * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
  2081.      * </p>
  2082.      * <p>
  2083.      * This method buffers the input internally, so there is no need to use a
  2084.      * {@link BufferedInputStream}.
  2085.      * </p>
  2086.      *
  2087.      * @param input the {@link InputStream} to read, not null
  2088.      * @param charsetName the name of the requested charset, null means platform default
  2089.      * @return the list of Strings, never null
  2090.      * @throws NullPointerException                         if the input is null
  2091.      * @throws UncheckedIOException                         if an I/O error occurs
  2092.      * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported
  2093.      * @since 1.1
  2094.      */
  2095.     public static List<String> readLines(final InputStream input, final String charsetName) throws UncheckedIOException {
  2096.         return readLines(input, Charsets.toCharset(charsetName));
  2097.     }

  2098.     /**
  2099.      * Gets the contents of a {@link Reader} as a list of Strings,
  2100.      * one entry per line.
  2101.      * <p>
  2102.      * This method buffers the input internally, so there is no need to use a
  2103.      * {@link BufferedReader}.
  2104.      * </p>
  2105.      *
  2106.      * @param reader the {@link Reader} to read, not null
  2107.      * @return the list of Strings, never null
  2108.      * @throws NullPointerException if the input is null
  2109.      * @throws UncheckedIOException if an I/O error occurs
  2110.      * @since 1.1
  2111.      */
  2112.     @SuppressWarnings("resource") // reader wraps input and is the responsibility of the caller.
  2113.     public static List<String> readLines(final Reader reader) throws UncheckedIOException {
  2114.         return toBufferedReader(reader).lines().collect(Collectors.toList());
  2115.     }

  2116.     /**
  2117.      * Gets the contents of a resource as a byte array.
  2118.      * <p>
  2119.      * Delegates to {@link #resourceToByteArray(String, ClassLoader) resourceToByteArray(String, null)}.
  2120.      * </p>
  2121.      *
  2122.      * @param name The resource name.
  2123.      * @return the requested byte array
  2124.      * @throws IOException if an I/O error occurs or the resource is not found.
  2125.      * @see #resourceToByteArray(String, ClassLoader)
  2126.      * @since 2.6
  2127.      */
  2128.     public static byte[] resourceToByteArray(final String name) throws IOException {
  2129.         return resourceToByteArray(name, null);
  2130.     }

  2131.     /**
  2132.      * Gets the contents of a resource as a byte array.
  2133.      * <p>
  2134.      * Delegates to {@link #resourceToURL(String, ClassLoader)}.
  2135.      * </p>
  2136.      *
  2137.      * @param name The resource name.
  2138.      * @param classLoader the class loader that the resolution of the resource is delegated to
  2139.      * @return the requested byte array
  2140.      * @throws IOException if an I/O error occurs or the resource is not found.
  2141.      * @see #resourceToURL(String, ClassLoader)
  2142.      * @since 2.6
  2143.      */
  2144.     public static byte[] resourceToByteArray(final String name, final ClassLoader classLoader) throws IOException {
  2145.         return toByteArray(resourceToURL(name, classLoader));
  2146.     }

  2147.     /**
  2148.      * Gets the contents of a resource as a String using the specified character encoding.
  2149.      * <p>
  2150.      * Delegates to {@link #resourceToString(String, Charset, ClassLoader) resourceToString(String, Charset, null)}.
  2151.      * </p>
  2152.      *
  2153.      * @param name The resource name.
  2154.      * @param charset the charset to use, null means platform default
  2155.      * @return the requested String
  2156.      * @throws IOException if an I/O error occurs or the resource is not found.
  2157.      * @see #resourceToString(String, Charset, ClassLoader)
  2158.      * @since 2.6
  2159.      */
  2160.     public static String resourceToString(final String name, final Charset charset) throws IOException {
  2161.         return resourceToString(name, charset, null);
  2162.     }

  2163.     /**
  2164.      * Gets the contents of a resource as a String using the specified character encoding.
  2165.      * <p>
  2166.      * Delegates to {@link #resourceToURL(String, ClassLoader)}.
  2167.      * </p>
  2168.      *
  2169.      * @param name The resource name.
  2170.      * @param charset the Charset to use, null means platform default
  2171.      * @param classLoader the class loader that the resolution of the resource is delegated to
  2172.      * @return the requested String
  2173.      * @throws IOException if an I/O error occurs.
  2174.      * @see #resourceToURL(String, ClassLoader)
  2175.      * @since 2.6
  2176.      */
  2177.     public static String resourceToString(final String name, final Charset charset, final ClassLoader classLoader) throws IOException {
  2178.         return toString(resourceToURL(name, classLoader), charset);
  2179.     }

  2180.     /**
  2181.      * Gets a URL pointing to the given resource.
  2182.      * <p>
  2183.      * Delegates to {@link #resourceToURL(String, ClassLoader) resourceToURL(String, null)}.
  2184.      * </p>
  2185.      *
  2186.      * @param name The resource name.
  2187.      * @return A URL object for reading the resource.
  2188.      * @throws IOException if the resource is not found.
  2189.      * @since 2.6
  2190.      */
  2191.     public static URL resourceToURL(final String name) throws IOException {
  2192.         return resourceToURL(name, null);
  2193.     }

  2194.     /**
  2195.      * Gets a URL pointing to the given resource.
  2196.      * <p>
  2197.      * If the {@code classLoader} is not null, call {@link ClassLoader#getResource(String)}, otherwise call
  2198.      * {@link Class#getResource(String) IOUtils.class.getResource(name)}.
  2199.      * </p>
  2200.      *
  2201.      * @param name The resource name.
  2202.      * @param classLoader Delegate to this class loader if not null
  2203.      * @return A URL object for reading the resource.
  2204.      * @throws IOException if the resource is not found.
  2205.      * @since 2.6
  2206.      */
  2207.     public static URL resourceToURL(final String name, final ClassLoader classLoader) throws IOException {
  2208.         // What about the thread context class loader?
  2209.         // What about the system class loader?
  2210.         final URL resource = classLoader == null ? IOUtils.class.getResource(name) : classLoader.getResource(name);
  2211.         if (resource == null) {
  2212.             throw new IOException("Resource not found: " + name);
  2213.         }
  2214.         return resource;
  2215.     }

  2216.     /**
  2217.      * Skips bytes from an input byte stream.
  2218.      * This implementation guarantees that it will read as many bytes
  2219.      * as possible before giving up; this may not always be the case for
  2220.      * skip() implementations in subclasses of {@link InputStream}.
  2221.      * <p>
  2222.      * Note that the implementation uses {@link InputStream#read(byte[], int, int)} rather
  2223.      * than delegating to {@link InputStream#skip(long)}.
  2224.      * This means that the method may be considerably less efficient than using the actual skip implementation,
  2225.      * this is done to guarantee that the correct number of bytes are skipped.
  2226.      * </p>
  2227.      *
  2228.      * @param input byte stream to skip
  2229.      * @param skip number of bytes to skip.
  2230.      * @return number of bytes actually skipped.
  2231.      * @throws IOException              if there is a problem reading the file
  2232.      * @throws IllegalArgumentException if toSkip is negative
  2233.      * @see InputStream#skip(long)
  2234.      * @see <a href="https://issues.apache.org/jira/browse/IO-203">IO-203 - Add skipFully() method for InputStreams</a>
  2235.      * @since 2.0
  2236.      */
  2237.     public static long skip(final InputStream input, final long skip) throws IOException {
  2238.         return skip(input, skip, IOUtils::getScratchByteArrayWriteOnly);
  2239.     }

  2240.     /**
  2241.      * Skips bytes from an input byte stream.
  2242.      * <p>
  2243.      * Intended for special cases when customization of the temporary buffer is needed because, for example, a nested input stream has requirements for the
  2244.      * bytes read. For example, when using {@link InflaterInputStream}s from multiple threads.
  2245.      * </p>
  2246.      * <p>
  2247.      * This implementation guarantees that it will read as many bytes as possible before giving up; this may not always be the case for skip() implementations
  2248.      * in subclasses of {@link InputStream}.
  2249.      * </p>
  2250.      * <p>
  2251.      * Note that the implementation uses {@link InputStream#read(byte[], int, int)} rather than delegating to {@link InputStream#skip(long)}. This means that
  2252.      * 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
  2253.      * skipped.
  2254.      * </p>
  2255.      *
  2256.      * @param input              byte stream to skip
  2257.      * @param skip             number of bytes to skip.
  2258.      * @param skipBufferSupplier Supplies the buffer to use for reading.
  2259.      * @return number of bytes actually skipped.
  2260.      * @throws IOException              if there is a problem reading the file
  2261.      * @throws IllegalArgumentException if toSkip is negative
  2262.      * @see InputStream#skip(long)
  2263.      * @see <a href="https://issues.apache.org/jira/browse/IO-203">IO-203 - Add skipFully() method for InputStreams</a>
  2264.      * @since 2.14.0
  2265.      */
  2266.     public static long skip(final InputStream input, final long skip, final Supplier<byte[]> skipBufferSupplier) throws IOException {
  2267.         if (skip < 0) {
  2268.             throw new IllegalArgumentException("Skip count must be non-negative, actual: " + skip);
  2269.         }
  2270.         //
  2271.         // No need to synchronize access to SCRATCH_BYTE_BUFFER_WO: We don't care if the buffer is written multiple
  2272.         // times or in parallel since the data is ignored. We reuse the same buffer, if the buffer size were variable or read-write,
  2273.         // we would need to synch or use a thread local to ensure some other thread safety.
  2274.         //
  2275.         long remain = skip;
  2276.         while (remain > 0) {
  2277.             final byte[] skipBuffer = skipBufferSupplier.get();
  2278.             // See https://issues.apache.org/jira/browse/IO-203 for why we use read() rather than delegating to skip()
  2279.             final long n = input.read(skipBuffer, 0, (int) Math.min(remain, skipBuffer.length));
  2280.             if (n < 0) { // EOF
  2281.                 break;
  2282.             }
  2283.             remain -= n;
  2284.         }
  2285.         return skip - remain;
  2286.     }

  2287.     /**
  2288.      * Skips bytes from a ReadableByteChannel.
  2289.      * This implementation guarantees that it will read as many bytes
  2290.      * as possible before giving up.
  2291.      *
  2292.      * @param input ReadableByteChannel to skip
  2293.      * @param toSkip number of bytes to skip.
  2294.      * @return number of bytes actually skipped.
  2295.      * @throws IOException              if there is a problem reading the ReadableByteChannel
  2296.      * @throws IllegalArgumentException if toSkip is negative
  2297.      * @since 2.5
  2298.      */
  2299.     public static long skip(final ReadableByteChannel input, final long toSkip) throws IOException {
  2300.         if (toSkip < 0) {
  2301.             throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip);
  2302.         }
  2303.         final ByteBuffer skipByteBuffer = ByteBuffer.allocate((int) Math.min(toSkip, DEFAULT_BUFFER_SIZE));
  2304.         long remain = toSkip;
  2305.         while (remain > 0) {
  2306.             skipByteBuffer.position(0);
  2307.             skipByteBuffer.limit((int) Math.min(remain, DEFAULT_BUFFER_SIZE));
  2308.             final int n = input.read(skipByteBuffer);
  2309.             if (n == EOF) {
  2310.                 break;
  2311.             }
  2312.             remain -= n;
  2313.         }
  2314.         return toSkip - remain;
  2315.     }

  2316.     /**
  2317.      * Skips characters from an input character stream.
  2318.      * This implementation guarantees that it will read as many characters
  2319.      * as possible before giving up; this may not always be the case for
  2320.      * skip() implementations in subclasses of {@link Reader}.
  2321.      * <p>
  2322.      * Note that the implementation uses {@link Reader#read(char[], int, int)} rather
  2323.      * than delegating to {@link Reader#skip(long)}.
  2324.      * This means that the method may be considerably less efficient than using the actual skip implementation,
  2325.      * this is done to guarantee that the correct number of characters are skipped.
  2326.      * </p>
  2327.      *
  2328.      * @param reader character stream to skip
  2329.      * @param toSkip number of characters to skip.
  2330.      * @return number of characters actually skipped.
  2331.      * @throws IOException              if there is a problem reading the file
  2332.      * @throws IllegalArgumentException if toSkip is negative
  2333.      * @see Reader#skip(long)
  2334.      * @see <a href="https://issues.apache.org/jira/browse/IO-203">IO-203 - Add skipFully() method for InputStreams</a>
  2335.      * @since 2.0
  2336.      */
  2337.     public static long skip(final Reader reader, final long toSkip) throws IOException {
  2338.         if (toSkip < 0) {
  2339.             throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip);
  2340.         }
  2341.         long remain = toSkip;
  2342.         while (remain > 0) {
  2343.             // See https://issues.apache.org/jira/browse/IO-203 for why we use read() rather than delegating to skip()
  2344.             final char[] charArray = getScratchCharArrayWriteOnly();
  2345.             final long n = reader.read(charArray, 0, (int) Math.min(remain, charArray.length));
  2346.             if (n < 0) { // EOF
  2347.                 break;
  2348.             }
  2349.             remain -= n;
  2350.         }
  2351.         return toSkip - remain;
  2352.     }

  2353.     /**
  2354.      * Skips the requested number of bytes or fail if there are not enough left.
  2355.      * <p>
  2356.      * This allows for the possibility that {@link InputStream#skip(long)} may
  2357.      * not skip as many bytes as requested (most likely because of reaching EOF).
  2358.      * </p>
  2359.      * <p>
  2360.      * Note that the implementation uses {@link #skip(InputStream, long)}.
  2361.      * This means that the method may be considerably less efficient than using the actual skip implementation,
  2362.      * this is done to guarantee that the correct number of characters are skipped.
  2363.      * </p>
  2364.      *
  2365.      * @param input stream to skip
  2366.      * @param toSkip the number of bytes to skip
  2367.      * @throws IOException              if there is a problem reading the file
  2368.      * @throws IllegalArgumentException if toSkip is negative
  2369.      * @throws EOFException             if the number of bytes skipped was incorrect
  2370.      * @see InputStream#skip(long)
  2371.      * @since 2.0
  2372.      */
  2373.     public static void skipFully(final InputStream input, final long toSkip) throws IOException {
  2374.         final long skipped = skip(input, toSkip, IOUtils::getScratchByteArrayWriteOnly);
  2375.         if (skipped != toSkip) {
  2376.             throw new EOFException("Bytes to skip: " + toSkip + " actual: " + skipped);
  2377.         }
  2378.     }

  2379.     /**
  2380.      * Skips the requested number of bytes or fail if there are not enough left.
  2381.      * <p>
  2382.      * Intended for special cases when customization of the temporary buffer is needed because, for example, a nested input stream has requirements for the
  2383.      * bytes read. For example, when using {@link InflaterInputStream}s from multiple threads.
  2384.      * </p>
  2385.      * <p>
  2386.      * This allows for the possibility that {@link InputStream#skip(long)} may not skip as many bytes as requested (most likely because of reaching EOF).
  2387.      * </p>
  2388.      * <p>
  2389.      * Note that the implementation uses {@link #skip(InputStream, long)}. This means that the method may be considerably less efficient than using the actual
  2390.      * skip implementation, this is done to guarantee that the correct number of characters are skipped.
  2391.      * </p>
  2392.      *
  2393.      * @param input              stream to skip
  2394.      * @param toSkip             the number of bytes to skip
  2395.      * @param skipBufferSupplier Supplies the buffer to use for reading.
  2396.      * @throws IOException              if there is a problem reading the file
  2397.      * @throws IllegalArgumentException if toSkip is negative
  2398.      * @throws EOFException             if the number of bytes skipped was incorrect
  2399.      * @see InputStream#skip(long)
  2400.      * @since 2.14.0
  2401.      */
  2402.     public static void skipFully(final InputStream input, final long toSkip, final Supplier<byte[]> skipBufferSupplier) throws IOException {
  2403.         if (toSkip < 0) {
  2404.             throw new IllegalArgumentException("Bytes to skip must not be negative: " + toSkip);
  2405.         }
  2406.         final long skipped = skip(input, toSkip, skipBufferSupplier);
  2407.         if (skipped != toSkip) {
  2408.             throw new EOFException("Bytes to skip: " + toSkip + " actual: " + skipped);
  2409.         }
  2410.     }

  2411.     /**
  2412.      * Skips the requested number of bytes or fail if there are not enough left.
  2413.      *
  2414.      * @param input ReadableByteChannel to skip
  2415.      * @param toSkip the number of bytes to skip
  2416.      * @throws IOException              if there is a problem reading the ReadableByteChannel
  2417.      * @throws IllegalArgumentException if toSkip is negative
  2418.      * @throws EOFException             if the number of bytes skipped was incorrect
  2419.      * @since 2.5
  2420.      */
  2421.     public static void skipFully(final ReadableByteChannel input, final long toSkip) throws IOException {
  2422.         if (toSkip < 0) {
  2423.             throw new IllegalArgumentException("Bytes to skip must not be negative: " + toSkip);
  2424.         }
  2425.         final long skipped = skip(input, toSkip);
  2426.         if (skipped != toSkip) {
  2427.             throw new EOFException("Bytes to skip: " + toSkip + " actual: " + skipped);
  2428.         }
  2429.     }

  2430.     /**
  2431.      * Skips the requested number of characters or fail if there are not enough left.
  2432.      * <p>
  2433.      * This allows for the possibility that {@link Reader#skip(long)} may
  2434.      * not skip as many characters as requested (most likely because of reaching EOF).
  2435.      * </p>
  2436.      * <p>
  2437.      * Note that the implementation uses {@link #skip(Reader, long)}.
  2438.      * This means that the method may be considerably less efficient than using the actual skip implementation,
  2439.      * this is done to guarantee that the correct number of characters are skipped.
  2440.      * </p>
  2441.      *
  2442.      * @param reader stream to skip
  2443.      * @param toSkip the number of characters to skip
  2444.      * @throws IOException              if there is a problem reading the file
  2445.      * @throws IllegalArgumentException if toSkip is negative
  2446.      * @throws EOFException             if the number of characters skipped was incorrect
  2447.      * @see Reader#skip(long)
  2448.      * @since 2.0
  2449.      */
  2450.     public static void skipFully(final Reader reader, final long toSkip) throws IOException {
  2451.         final long skipped = skip(reader, toSkip);
  2452.         if (skipped != toSkip) {
  2453.             throw new EOFException("Chars to skip: " + toSkip + " actual: " + skipped);
  2454.         }
  2455.     }

  2456.     /**
  2457.      * Fetches entire contents of an {@link InputStream} and represent
  2458.      * same data as result InputStream.
  2459.      * <p>
  2460.      * This method is useful where,
  2461.      * </p>
  2462.      * <ul>
  2463.      * <li>Source InputStream is slow.</li>
  2464.      * <li>It has network resources associated, so we cannot keep it open for
  2465.      * long time.</li>
  2466.      * <li>It has network timeout associated.</li>
  2467.      * </ul>
  2468.      * <p>
  2469.      * It can be used in favor of {@link #toByteArray(InputStream)}, since it
  2470.      * avoids unnecessary allocation and copy of byte[].<br>
  2471.      * This method buffers the input internally, so there is no need to use a
  2472.      * {@link BufferedInputStream}.
  2473.      * </p>
  2474.      *
  2475.      * @param input Stream to be fully buffered.
  2476.      * @return A fully buffered stream.
  2477.      * @throws IOException if an I/O error occurs.
  2478.      * @since 2.0
  2479.      */
  2480.     public static InputStream toBufferedInputStream(final InputStream input) throws IOException {
  2481.         return ByteArrayOutputStream.toBufferedInputStream(input);
  2482.     }

  2483.     /**
  2484.      * Fetches entire contents of an {@link InputStream} and represent
  2485.      * same data as result InputStream.
  2486.      * <p>
  2487.      * This method is useful where,
  2488.      * </p>
  2489.      * <ul>
  2490.      * <li>Source InputStream is slow.</li>
  2491.      * <li>It has network resources associated, so we cannot keep it open for
  2492.      * long time.</li>
  2493.      * <li>It has network timeout associated.</li>
  2494.      * </ul>
  2495.      * <p>
  2496.      * It can be used in favor of {@link #toByteArray(InputStream)}, since it
  2497.      * avoids unnecessary allocation and copy of byte[].<br>
  2498.      * This method buffers the input internally, so there is no need to use a
  2499.      * {@link BufferedInputStream}.
  2500.      * </p>
  2501.      *
  2502.      * @param input Stream to be fully buffered.
  2503.      * @param size the initial buffer size
  2504.      * @return A fully buffered stream.
  2505.      * @throws IOException if an I/O error occurs.
  2506.      * @since 2.5
  2507.      */
  2508.     public static InputStream toBufferedInputStream(final InputStream input, final int size) throws IOException {
  2509.         return ByteArrayOutputStream.toBufferedInputStream(input, size);
  2510.     }

  2511.     /**
  2512.      * Returns the given reader if it is a {@link BufferedReader}, otherwise creates a BufferedReader from the given
  2513.      * reader.
  2514.      *
  2515.      * @param reader the reader to wrap or return (not null)
  2516.      * @return the given reader or a new {@link BufferedReader} for the given reader
  2517.      * @throws NullPointerException if the input parameter is null
  2518.      * @see #buffer(Reader)
  2519.      * @since 2.2
  2520.      */
  2521.     public static BufferedReader toBufferedReader(final Reader reader) {
  2522.         return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);
  2523.     }

  2524.     /**
  2525.      * Returns the given reader if it is a {@link BufferedReader}, otherwise creates a BufferedReader from the given
  2526.      * reader.
  2527.      *
  2528.      * @param reader the reader to wrap or return (not null)
  2529.      * @param size the buffer size, if a new BufferedReader is created.
  2530.      * @return the given reader or a new {@link BufferedReader} for the given reader
  2531.      * @throws NullPointerException if the input parameter is null
  2532.      * @see #buffer(Reader)
  2533.      * @since 2.5
  2534.      */
  2535.     public static BufferedReader toBufferedReader(final Reader reader, final int size) {
  2536.         return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader, size);
  2537.     }

  2538.     /**
  2539.      * Gets the contents of an {@link InputStream} as a {@code byte[]}.
  2540.      * <p>
  2541.      * This method buffers the input internally, so there is no need to use a
  2542.      * {@link BufferedInputStream}.
  2543.      * </p>
  2544.      *
  2545.      * @param inputStream the {@link InputStream} to read.
  2546.      * @return the requested byte array.
  2547.      * @throws NullPointerException if the InputStream is {@code null}.
  2548.      * @throws IOException if an I/O error occurs or reading more than {@link Integer#MAX_VALUE} occurs.
  2549.      */
  2550.     public static byte[] toByteArray(final InputStream inputStream) throws IOException {
  2551.         // We use a ThresholdingOutputStream to avoid reading AND writing more than Integer.MAX_VALUE.
  2552.         try (UnsynchronizedByteArrayOutputStream ubaOutput = UnsynchronizedByteArrayOutputStream.builder().get();
  2553.             ThresholdingOutputStream thresholdOutput = new ThresholdingOutputStream(Integer.MAX_VALUE, os -> {
  2554.                 throw new IllegalArgumentException(String.format("Cannot read more than %,d into a byte array", Integer.MAX_VALUE));
  2555.             }, os -> ubaOutput)) {
  2556.             copy(inputStream, thresholdOutput);
  2557.             return ubaOutput.toByteArray();
  2558.         }
  2559.     }

  2560.     /**
  2561.      * Gets the contents of an {@link InputStream} as a {@code byte[]}. Use this method instead of
  2562.      * {@link #toByteArray(InputStream)} when {@link InputStream} size is known.
  2563.      *
  2564.      * @param input the {@link InputStream} to read.
  2565.      * @param size the size of {@link InputStream} to read, where 0 &lt; {@code size} &lt;= length of input stream.
  2566.      * @return byte [] of length {@code size}.
  2567.      * @throws IOException if an I/O error occurs or {@link InputStream} length is smaller than parameter {@code size}.
  2568.      * @throws IllegalArgumentException if {@code size} is less than zero.
  2569.      * @since 2.1
  2570.      */
  2571.     public static byte[] toByteArray(final InputStream input, final int size) throws IOException {
  2572.         if (size == 0) {
  2573.             return EMPTY_BYTE_ARRAY;
  2574.         }
  2575.         return toByteArray(Objects.requireNonNull(input, "input")::read, size);
  2576.     }

  2577.     /**
  2578.      * Gets contents of an {@link InputStream} as a {@code byte[]}.
  2579.      * Use this method instead of {@link #toByteArray(InputStream)}
  2580.      * when {@link InputStream} size is known.
  2581.      * <strong>NOTE:</strong> the method checks that the length can safely be cast to an int without truncation
  2582.      * before using {@link IOUtils#toByteArray(InputStream, int)} to read into the byte array.
  2583.      * (Arrays can have no more than Integer.MAX_VALUE entries anyway)
  2584.      *
  2585.      * @param input the {@link InputStream} to read
  2586.      * @param size the size of {@link InputStream} to read, where 0 &lt; {@code size} &lt;= min(Integer.MAX_VALUE, length of input stream).
  2587.      * @return byte [] the requested byte array, of length {@code size}
  2588.      * @throws IOException              if an I/O error occurs or {@link InputStream} length is less than {@code size}
  2589.      * @throws IllegalArgumentException if size is less than zero or size is greater than Integer.MAX_VALUE
  2590.      * @see IOUtils#toByteArray(InputStream, int)
  2591.      * @since 2.1
  2592.      */
  2593.     public static byte[] toByteArray(final InputStream input, final long size) throws IOException {
  2594.         if (size > Integer.MAX_VALUE) {
  2595.             throw new IllegalArgumentException("Size cannot be greater than Integer max value: " + size);
  2596.         }
  2597.         return toByteArray(input, (int) size);
  2598.     }

  2599.     /**
  2600.      * Gets the contents of an input as a {@code byte[]}.
  2601.      *
  2602.      * @param input the input to read.
  2603.      * @param size the size of the input to read, where 0 &lt; {@code size} &lt;= length of input.
  2604.      * @return byte [] of length {@code size}.
  2605.      * @throws IOException if an I/O error occurs or input length is smaller than parameter {@code size}.
  2606.      * @throws IllegalArgumentException if {@code size} is less than zero.
  2607.      */
  2608.     static byte[] toByteArray(final IOTriFunction<byte[], Integer, Integer, Integer> input, final int size) throws IOException {

  2609.         if (size < 0) {
  2610.             throw new IllegalArgumentException("Size must be equal or greater than zero: " + size);
  2611.         }

  2612.         if (size == 0) {
  2613.             return EMPTY_BYTE_ARRAY;
  2614.         }

  2615.         final byte[] data = byteArray(size);
  2616.         int offset = 0;
  2617.         int read;

  2618.         while (offset < size && (read = input.apply(data, offset, size - offset)) != EOF) {
  2619.             offset += read;
  2620.         }

  2621.         if (offset != size) {
  2622.             throw new IOException("Unexpected read size, current: " + offset + ", expected: " + size);
  2623.         }

  2624.         return data;
  2625.     }

  2626.     /**
  2627.      * Gets the contents of a {@link Reader} as a {@code byte[]}
  2628.      * using the virtual machine's {@link Charset#defaultCharset() default charset}.
  2629.      * <p>
  2630.      * This method buffers the input internally, so there is no need to use a
  2631.      * {@link BufferedReader}.
  2632.      * </p>
  2633.      *
  2634.      * @param reader the {@link Reader} to read
  2635.      * @return the requested byte array
  2636.      * @throws NullPointerException if the input is null
  2637.      * @throws IOException          if an I/O error occurs
  2638.      * @deprecated Use {@link #toByteArray(Reader, Charset)} instead
  2639.      */
  2640.     @Deprecated
  2641.     public static byte[] toByteArray(final Reader reader) throws IOException {
  2642.         return toByteArray(reader, Charset.defaultCharset());
  2643.     }

  2644.     /**
  2645.      * Gets the contents of a {@link Reader} as a {@code byte[]}
  2646.      * using the specified character encoding.
  2647.      * <p>
  2648.      * This method buffers the input internally, so there is no need to use a
  2649.      * {@link BufferedReader}.
  2650.      * </p>
  2651.      *
  2652.      * @param reader the {@link Reader} to read
  2653.      * @param charset the charset to use, null means platform default
  2654.      * @return the requested byte array
  2655.      * @throws NullPointerException if the input is null
  2656.      * @throws IOException          if an I/O error occurs
  2657.      * @since 2.3
  2658.      */
  2659.     public static byte[] toByteArray(final Reader reader, final Charset charset) throws IOException {
  2660.         try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
  2661.             copy(reader, output, charset);
  2662.             return output.toByteArray();
  2663.         }
  2664.     }

  2665.     /**
  2666.      * Gets the contents of a {@link Reader} as a {@code byte[]}
  2667.      * using the specified character encoding.
  2668.      * <p>
  2669.      * Character encoding names can be found at
  2670.      * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
  2671.      * </p>
  2672.      * <p>
  2673.      * This method buffers the input internally, so there is no need to use a
  2674.      * {@link BufferedReader}.
  2675.      * </p>
  2676.      *
  2677.      * @param reader the {@link Reader} to read
  2678.      * @param charsetName the name of the requested charset, null means platform default
  2679.      * @return the requested byte array
  2680.      * @throws NullPointerException                         if the input is null
  2681.      * @throws IOException                                  if an I/O error occurs
  2682.      * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported
  2683.      * @since 1.1
  2684.      */
  2685.     public static byte[] toByteArray(final Reader reader, final String charsetName) throws IOException {
  2686.         return toByteArray(reader, Charsets.toCharset(charsetName));
  2687.     }

  2688.     /**
  2689.      * Gets the contents of a {@link String} as a {@code byte[]}
  2690.      * using the virtual machine's {@link Charset#defaultCharset() default charset}.
  2691.      * <p>
  2692.      * This is the same as {@link String#getBytes()}.
  2693.      * </p>
  2694.      *
  2695.      * @param input the {@link String} to convert
  2696.      * @return the requested byte array
  2697.      * @throws NullPointerException if the input is null
  2698.      * @deprecated Use {@link String#getBytes()} instead
  2699.      */
  2700.     @Deprecated
  2701.     public static byte[] toByteArray(final String input) {
  2702.         // make explicit the use of the default charset
  2703.         return input.getBytes(Charset.defaultCharset());
  2704.     }

  2705.     /**
  2706.      * Gets the contents of a {@link URI} as a {@code byte[]}.
  2707.      *
  2708.      * @param uri the {@link URI} to read
  2709.      * @return the requested byte array
  2710.      * @throws NullPointerException if the uri is null
  2711.      * @throws IOException          if an I/O exception occurs
  2712.      * @since 2.4
  2713.      */
  2714.     public static byte[] toByteArray(final URI uri) throws IOException {
  2715.         return toByteArray(uri.toURL());
  2716.     }

  2717.     /**
  2718.      * Gets the contents of a {@link URL} as a {@code byte[]}.
  2719.      *
  2720.      * @param url the {@link URL} to read
  2721.      * @return the requested byte array
  2722.      * @throws NullPointerException if the input is null
  2723.      * @throws IOException          if an I/O exception occurs
  2724.      * @since 2.4
  2725.      */
  2726.     public static byte[] toByteArray(final URL url) throws IOException {
  2727.         try (CloseableURLConnection urlConnection = CloseableURLConnection.open(url)) {
  2728.             return toByteArray(urlConnection);
  2729.         }
  2730.     }

  2731.     /**
  2732.      * Gets the contents of a {@link URLConnection} as a {@code byte[]}.
  2733.      *
  2734.      * @param urlConnection the {@link URLConnection} to read.
  2735.      * @return the requested byte array.
  2736.      * @throws NullPointerException if the urlConn is null.
  2737.      * @throws IOException if an I/O exception occurs.
  2738.      * @since 2.4
  2739.      */
  2740.     public static byte[] toByteArray(final URLConnection urlConnection) throws IOException {
  2741.         try (InputStream inputStream = urlConnection.getInputStream()) {
  2742.             return toByteArray(inputStream);
  2743.         }
  2744.     }

  2745.     /**
  2746.      * Gets the contents of an {@link InputStream} as a character array
  2747.      * using the virtual machine's {@link Charset#defaultCharset() default charset}.
  2748.      * <p>
  2749.      * This method buffers the input internally, so there is no need to use a
  2750.      * {@link BufferedInputStream}.
  2751.      * </p>
  2752.      *
  2753.      * @param inputStream the {@link InputStream} to read
  2754.      * @return the requested character array
  2755.      * @throws NullPointerException if the input is null
  2756.      * @throws IOException          if an I/O error occurs
  2757.      * @since 1.1
  2758.      * @deprecated Use {@link #toCharArray(InputStream, Charset)} instead
  2759.      */
  2760.     @Deprecated
  2761.     public static char[] toCharArray(final InputStream inputStream) throws IOException {
  2762.         return toCharArray(inputStream, Charset.defaultCharset());
  2763.     }

  2764.     /**
  2765.      * Gets the contents of an {@link InputStream} as a character array
  2766.      * using the specified character encoding.
  2767.      * <p>
  2768.      * This method buffers the input internally, so there is no need to use a
  2769.      * {@link BufferedInputStream}.
  2770.      * </p>
  2771.      *
  2772.      * @param inputStream the {@link InputStream} to read
  2773.      * @param charset the charset to use, null means platform default
  2774.      * @return the requested character array
  2775.      * @throws NullPointerException if the input is null
  2776.      * @throws IOException          if an I/O error occurs
  2777.      * @since 2.3
  2778.      */
  2779.     public static char[] toCharArray(final InputStream inputStream, final Charset charset)
  2780.             throws IOException {
  2781.         final CharArrayWriter writer = new CharArrayWriter();
  2782.         copy(inputStream, writer, charset);
  2783.         return writer.toCharArray();
  2784.     }

  2785.     /**
  2786.      * Gets the contents of an {@link InputStream} as a character array
  2787.      * using the specified character encoding.
  2788.      * <p>
  2789.      * Character encoding names can be found at
  2790.      * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
  2791.      * </p>
  2792.      * <p>
  2793.      * This method buffers the input internally, so there is no need to use a
  2794.      * {@link BufferedInputStream}.
  2795.      * </p>
  2796.      *
  2797.      * @param inputStream the {@link InputStream} to read
  2798.      * @param charsetName the name of the requested charset, null means platform default
  2799.      * @return the requested character array
  2800.      * @throws NullPointerException                         if the input is null
  2801.      * @throws IOException                                  if an I/O error occurs
  2802.      * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported
  2803.      * @since 1.1
  2804.      */
  2805.     public static char[] toCharArray(final InputStream inputStream, final String charsetName) throws IOException {
  2806.         return toCharArray(inputStream, Charsets.toCharset(charsetName));
  2807.     }

  2808.     /**
  2809.      * Gets the contents of a {@link Reader} as a character array.
  2810.      * <p>
  2811.      * This method buffers the input internally, so there is no need to use a
  2812.      * {@link BufferedReader}.
  2813.      * </p>
  2814.      *
  2815.      * @param reader the {@link Reader} to read
  2816.      * @return the requested character array
  2817.      * @throws NullPointerException if the input is null
  2818.      * @throws IOException          if an I/O error occurs
  2819.      * @since 1.1
  2820.      */
  2821.     public static char[] toCharArray(final Reader reader) throws IOException {
  2822.         final CharArrayWriter sw = new CharArrayWriter();
  2823.         copy(reader, sw);
  2824.         return sw.toCharArray();
  2825.     }

  2826.     /**
  2827.      * Converts the specified CharSequence to an input stream, encoded as bytes
  2828.      * using the virtual machine's {@link Charset#defaultCharset() default charset}.
  2829.      *
  2830.      * @param input the CharSequence to convert
  2831.      * @return an input stream
  2832.      * @since 2.0
  2833.      * @deprecated Use {@link #toInputStream(CharSequence, Charset)} instead
  2834.      */
  2835.     @Deprecated
  2836.     public static InputStream toInputStream(final CharSequence input) {
  2837.         return toInputStream(input, Charset.defaultCharset());
  2838.     }

  2839.     /**
  2840.      * Converts the specified CharSequence to an input stream, encoded as bytes
  2841.      * using the specified character encoding.
  2842.      *
  2843.      * @param input the CharSequence to convert
  2844.      * @param charset the charset to use, null means platform default
  2845.      * @return an input stream
  2846.      * @since 2.3
  2847.      */
  2848.     public static InputStream toInputStream(final CharSequence input, final Charset charset) {
  2849.         return toInputStream(input.toString(), charset);
  2850.     }

  2851.     /**
  2852.      * Converts the specified CharSequence to an input stream, encoded as bytes
  2853.      * using the specified character encoding.
  2854.      * <p>
  2855.      * Character encoding names can be found at
  2856.      * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
  2857.      * </p>
  2858.      *
  2859.      * @param input the CharSequence to convert
  2860.      * @param charsetName the name of the requested charset, null means platform default
  2861.      * @return an input stream
  2862.      * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported
  2863.      * @since 2.0
  2864.      */
  2865.     public static InputStream toInputStream(final CharSequence input, final String charsetName) {
  2866.         return toInputStream(input, Charsets.toCharset(charsetName));
  2867.     }

  2868.     /**
  2869.      * Converts the specified string to an input stream, encoded as bytes
  2870.      * using the virtual machine's {@link Charset#defaultCharset() default charset}.
  2871.      *
  2872.      * @param input the string to convert
  2873.      * @return an input stream
  2874.      * @since 1.1
  2875.      * @deprecated Use {@link #toInputStream(String, Charset)} instead
  2876.      */
  2877.     @Deprecated
  2878.     public static InputStream toInputStream(final String input) {
  2879.         return toInputStream(input, Charset.defaultCharset());
  2880.     }

  2881.     /**
  2882.      * Converts the specified string to an input stream, encoded as bytes
  2883.      * using the specified character encoding.
  2884.      *
  2885.      * @param input the string to convert
  2886.      * @param charset the charset to use, null means platform default
  2887.      * @return an input stream
  2888.      * @since 2.3
  2889.      */
  2890.     public static InputStream toInputStream(final String input, final Charset charset) {
  2891.         return new ByteArrayInputStream(input.getBytes(Charsets.toCharset(charset)));
  2892.     }

  2893.     /**
  2894.      * Converts the specified string to an input stream, encoded as bytes
  2895.      * using the specified character encoding.
  2896.      * <p>
  2897.      * Character encoding names can be found at
  2898.      * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
  2899.      * </p>
  2900.      *
  2901.      * @param input the string to convert
  2902.      * @param charsetName the name of the requested charset, null means platform default
  2903.      * @return an input stream
  2904.      * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported
  2905.      * @since 1.1
  2906.      */
  2907.     public static InputStream toInputStream(final String input, final String charsetName) {
  2908.         return new ByteArrayInputStream(input.getBytes(Charsets.toCharset(charsetName)));
  2909.     }

  2910.     /**
  2911.      * Gets the contents of a {@code byte[]} as a String
  2912.      * using the virtual machine's {@link Charset#defaultCharset() default charset}.
  2913.      *
  2914.      * @param input the byte array to read
  2915.      * @return the requested String
  2916.      * @throws NullPointerException if the input is null
  2917.      * @deprecated Use {@link String#String(byte[])} instead
  2918.      */
  2919.     @Deprecated
  2920.     public static String toString(final byte[] input) {
  2921.         // make explicit the use of the default charset
  2922.         return new String(input, Charset.defaultCharset());
  2923.     }

  2924.     /**
  2925.      * Gets the contents of a {@code byte[]} as a String
  2926.      * using the specified character encoding.
  2927.      * <p>
  2928.      * Character encoding names can be found at
  2929.      * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
  2930.      * </p>
  2931.      *
  2932.      * @param input the byte array to read
  2933.      * @param charsetName the name of the requested charset, null means platform default
  2934.      * @return the requested String
  2935.      * @throws NullPointerException if the input is null
  2936.      */
  2937.     public static String toString(final byte[] input, final String charsetName) {
  2938.         return new String(input, Charsets.toCharset(charsetName));
  2939.     }

  2940.     /**
  2941.      * Gets the contents of an {@link InputStream} as a String
  2942.      * using the virtual machine's {@link Charset#defaultCharset() default charset}.
  2943.      * <p>
  2944.      * This method buffers the input internally, so there is no need to use a
  2945.      * {@link BufferedInputStream}.
  2946.      * </p>
  2947.      *
  2948.      * @param input the {@link InputStream} to read
  2949.      * @return the requested String
  2950.      * @throws NullPointerException if the input is null
  2951.      * @throws IOException          if an I/O error occurs
  2952.      * @deprecated Use {@link #toString(InputStream, Charset)} instead
  2953.      */
  2954.     @Deprecated
  2955.     public static String toString(final InputStream input) throws IOException {
  2956.         return toString(input, Charset.defaultCharset());
  2957.     }

  2958.     /**
  2959.      * Gets the contents of an {@link InputStream} as a String
  2960.      * using the specified character encoding.
  2961.      * <p>
  2962.      * This method buffers the input internally, so there is no need to use a
  2963.      * {@link BufferedInputStream}.
  2964.      * </p>
  2965.      *
  2966.      * @param input the {@link InputStream} to read
  2967.      * @param charset the charset to use, null means platform default
  2968.      * @return the requested String
  2969.      * @throws NullPointerException if the input is null
  2970.      * @throws IOException          if an I/O error occurs
  2971.      * @since 2.3
  2972.      */
  2973.     public static String toString(final InputStream input, final Charset charset) throws IOException {
  2974.         try (StringBuilderWriter sw = new StringBuilderWriter()) {
  2975.             copy(input, sw, charset);
  2976.             return sw.toString();
  2977.         }
  2978.     }

  2979.     /**
  2980.      * Gets the contents of an {@link InputStream} as a String
  2981.      * using the specified character encoding.
  2982.      * <p>
  2983.      * Character encoding names can be found at
  2984.      * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
  2985.      * </p>
  2986.      * <p>
  2987.      * This method buffers the input internally, so there is no need to use a
  2988.      * {@link BufferedInputStream}.
  2989.      * </p>
  2990.      *
  2991.      * @param input the {@link InputStream} to read
  2992.      * @param charsetName the name of the requested charset, null means platform default
  2993.      * @return the requested String
  2994.      * @throws NullPointerException                         if the input is null
  2995.      * @throws IOException                                  if an I/O error occurs
  2996.      * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported
  2997.      */
  2998.     public static String toString(final InputStream input, final String charsetName)
  2999.             throws IOException {
  3000.         return toString(input, Charsets.toCharset(charsetName));
  3001.     }

  3002.     /**
  3003.      * Gets the contents of an {@link InputStream} from a supplier as a String
  3004.      * using the specified character encoding.
  3005.      * <p>
  3006.      * This method buffers the input internally, so there is no need to use a
  3007.      * {@link BufferedInputStream}.
  3008.      * </p>
  3009.      *
  3010.      * @param input supplies the {@link InputStream} to read
  3011.      * @param charset the charset to use, null means platform default
  3012.      * @return the requested String
  3013.      * @throws NullPointerException if the input is null
  3014.      * @throws IOException          if an I/O error occurs
  3015.      * @since 2.12.0
  3016.      */
  3017.     public static String toString(final IOSupplier<InputStream> input, final Charset charset) throws IOException {
  3018.         return toString(input, charset, () -> {
  3019.             throw new NullPointerException("input");
  3020.         });
  3021.     }

  3022.     /**
  3023.      * Gets the contents of an {@link InputStream} from a supplier as a String
  3024.      * using the specified character encoding.
  3025.      * <p>
  3026.      * This method buffers the input internally, so there is no need to use a
  3027.      * {@link BufferedInputStream}.
  3028.      * </p>
  3029.      *
  3030.      * @param input supplies the {@link InputStream} to read
  3031.      * @param charset the charset to use, null means platform default
  3032.      * @param defaultString the default return value if the supplier or its value is null.
  3033.      * @return the requested String
  3034.      * @throws NullPointerException if the input is null
  3035.      * @throws IOException          if an I/O error occurs
  3036.      * @since 2.12.0
  3037.      */
  3038.     public static String toString(final IOSupplier<InputStream> input, final Charset charset, final IOSupplier<String> defaultString) throws IOException {
  3039.         if (input == null) {
  3040.             return defaultString.get();
  3041.         }
  3042.         try (InputStream inputStream = input.get()) {
  3043.             return inputStream != null ? toString(inputStream, charset) : defaultString.get();
  3044.         }
  3045.     }

  3046.     /**
  3047.      * Gets the contents of a {@link Reader} as a String.
  3048.      * <p>
  3049.      * This method buffers the input internally, so there is no need to use a
  3050.      * {@link BufferedReader}.
  3051.      * </p>
  3052.      *
  3053.      * @param reader the {@link Reader} to read
  3054.      * @return the requested String
  3055.      * @throws NullPointerException if the input is null
  3056.      * @throws IOException          if an I/O error occurs
  3057.      */
  3058.     public static String toString(final Reader reader) throws IOException {
  3059.         try (StringBuilderWriter sw = new StringBuilderWriter()) {
  3060.             copy(reader, sw);
  3061.             return sw.toString();
  3062.         }
  3063.     }

  3064.     /**
  3065.      * Gets the contents at the given URI using the virtual machine's {@link Charset#defaultCharset() default charset}.
  3066.      *
  3067.      * @param uri The URI source.
  3068.      * @return The contents of the URL as a String.
  3069.      * @throws IOException if an I/O exception occurs.
  3070.      * @since 2.1
  3071.      * @deprecated Use {@link #toString(URI, Charset)} instead
  3072.      */
  3073.     @Deprecated
  3074.     public static String toString(final URI uri) throws IOException {
  3075.         return toString(uri, Charset.defaultCharset());
  3076.     }

  3077.     /**
  3078.      * Gets the contents at the given URI.
  3079.      *
  3080.      * @param uri The URI source.
  3081.      * @param encoding The encoding name for the URL contents.
  3082.      * @return The contents of the URL as a String.
  3083.      * @throws IOException if an I/O exception occurs.
  3084.      * @since 2.3.
  3085.      */
  3086.     public static String toString(final URI uri, final Charset encoding) throws IOException {
  3087.         return toString(uri.toURL(), Charsets.toCharset(encoding));
  3088.     }

  3089.     /**
  3090.      * Gets the contents at the given URI.
  3091.      *
  3092.      * @param uri The URI source.
  3093.      * @param charsetName The encoding name for the URL contents.
  3094.      * @return The contents of the URL as a String.
  3095.      * @throws IOException                                  if an I/O exception occurs.
  3096.      * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported
  3097.      * @since 2.1
  3098.      */
  3099.     public static String toString(final URI uri, final String charsetName) throws IOException {
  3100.         return toString(uri, Charsets.toCharset(charsetName));
  3101.     }

  3102.     /**
  3103.      * Gets the contents at the given URL using the virtual machine's {@link Charset#defaultCharset() default charset}.
  3104.      *
  3105.      * @param url The URL source.
  3106.      * @return The contents of the URL as a String.
  3107.      * @throws IOException if an I/O exception occurs.
  3108.      * @since 2.1
  3109.      * @deprecated Use {@link #toString(URL, Charset)} instead
  3110.      */
  3111.     @Deprecated
  3112.     public static String toString(final URL url) throws IOException {
  3113.         return toString(url, Charset.defaultCharset());
  3114.     }

  3115.     /**
  3116.      * Gets the contents at the given URL.
  3117.      *
  3118.      * @param url The URL source.
  3119.      * @param encoding The encoding name for the URL contents.
  3120.      * @return The contents of the URL as a String.
  3121.      * @throws IOException if an I/O exception occurs.
  3122.      * @since 2.3
  3123.      */
  3124.     public static String toString(final URL url, final Charset encoding) throws IOException {
  3125.         return toString(url::openStream, encoding);
  3126.     }

  3127.     /**
  3128.      * Gets the contents at the given URL.
  3129.      *
  3130.      * @param url The URL source.
  3131.      * @param charsetName The encoding name for the URL contents.
  3132.      * @return The contents of the URL as a String.
  3133.      * @throws IOException                                  if an I/O exception occurs.
  3134.      * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported
  3135.      * @since 2.1
  3136.      */
  3137.     public static String toString(final URL url, final String charsetName) throws IOException {
  3138.         return toString(url, Charsets.toCharset(charsetName));
  3139.     }

  3140.     /**
  3141.      * Writes bytes from a {@code byte[]} to an {@link OutputStream}.
  3142.      *
  3143.      * @param data the byte array to write, do not modify during output,
  3144.      * null ignored
  3145.      * @param output the {@link OutputStream} to write to
  3146.      * @throws NullPointerException if output is null
  3147.      * @throws IOException          if an I/O error occurs
  3148.      * @since 1.1
  3149.      */
  3150.     public static void write(final byte[] data, final OutputStream output)
  3151.             throws IOException {
  3152.         if (data != null) {
  3153.             output.write(data);
  3154.         }
  3155.     }

  3156.     /**
  3157.      * Writes bytes from a {@code byte[]} to chars on a {@link Writer}
  3158.      * using the virtual machine's {@link Charset#defaultCharset() default charset}.
  3159.      * <p>
  3160.      * This method uses {@link String#String(byte[])}.
  3161.      * </p>
  3162.      *
  3163.      * @param data the byte array to write, do not modify during output,
  3164.      * null ignored
  3165.      * @param writer the {@link Writer} to write to
  3166.      * @throws NullPointerException if output is null
  3167.      * @throws IOException          if an I/O error occurs
  3168.      * @since 1.1
  3169.      * @deprecated Use {@link #write(byte[], Writer, Charset)} instead
  3170.      */
  3171.     @Deprecated
  3172.     public static void write(final byte[] data, final Writer writer) throws IOException {
  3173.         write(data, writer, Charset.defaultCharset());
  3174.     }

  3175.     /**
  3176.      * Writes bytes from a {@code byte[]} to chars on a {@link Writer}
  3177.      * using the specified character encoding.
  3178.      * <p>
  3179.      * This method uses {@link String#String(byte[], String)}.
  3180.      * </p>
  3181.      *
  3182.      * @param data the byte array to write, do not modify during output,
  3183.      * null ignored
  3184.      * @param writer the {@link Writer} to write to
  3185.      * @param charset the charset to use, null means platform default
  3186.      * @throws NullPointerException if output is null
  3187.      * @throws IOException          if an I/O error occurs
  3188.      * @since 2.3
  3189.      */
  3190.     public static void write(final byte[] data, final Writer writer, final Charset charset) throws IOException {
  3191.         if (data != null) {
  3192.             writer.write(new String(data, Charsets.toCharset(charset)));
  3193.         }
  3194.     }

  3195.     /**
  3196.      * Writes bytes from a {@code byte[]} to chars on a {@link Writer}
  3197.      * using the specified character encoding.
  3198.      * <p>
  3199.      * Character encoding names can be found at
  3200.      * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
  3201.      * </p>
  3202.      * <p>
  3203.      * This method uses {@link String#String(byte[], String)}.
  3204.      * </p>
  3205.      *
  3206.      * @param data the byte array to write, do not modify during output,
  3207.      * null ignored
  3208.      * @param writer the {@link Writer} to write to
  3209.      * @param charsetName the name of the requested charset, null means platform default
  3210.      * @throws NullPointerException                         if output is null
  3211.      * @throws IOException                                  if an I/O error occurs
  3212.      * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported
  3213.      * @since 1.1
  3214.      */
  3215.     public static void write(final byte[] data, final Writer writer, final String charsetName) throws IOException {
  3216.         write(data, writer, Charsets.toCharset(charsetName));
  3217.     }

  3218.     /**
  3219.      * Writes chars from a {@code char[]} to bytes on an
  3220.      * {@link OutputStream}.
  3221.      * <p>
  3222.      * This method uses the virtual machine's {@link Charset#defaultCharset() default charset}.
  3223.      * </p>
  3224.      *
  3225.      * @param data the char array to write, do not modify during output,
  3226.      * null ignored
  3227.      * @param output the {@link OutputStream} to write to
  3228.      * @throws NullPointerException if output is null
  3229.      * @throws IOException          if an I/O error occurs
  3230.      * @since 1.1
  3231.      * @deprecated Use {@link #write(char[], OutputStream, Charset)} instead
  3232.      */
  3233.     @Deprecated
  3234.     public static void write(final char[] data, final OutputStream output)
  3235.             throws IOException {
  3236.         write(data, output, Charset.defaultCharset());
  3237.     }

  3238.     /**
  3239.      * Writes chars from a {@code char[]} to bytes on an
  3240.      * {@link OutputStream} using the specified character encoding.
  3241.      * <p>
  3242.      * This method uses {@link String#String(char[])} and
  3243.      * {@link String#getBytes(String)}.
  3244.      * </p>
  3245.      *
  3246.      * @param data the char array to write, do not modify during output,
  3247.      * null ignored
  3248.      * @param output the {@link OutputStream} to write to
  3249.      * @param charset the charset to use, null means platform default
  3250.      * @throws NullPointerException if output is null
  3251.      * @throws IOException          if an I/O error occurs
  3252.      * @since 2.3
  3253.      */
  3254.     public static void write(final char[] data, final OutputStream output, final Charset charset) throws IOException {
  3255.         if (data != null) {
  3256.             write(new String(data), output, charset);
  3257.         }
  3258.     }

  3259.     /**
  3260.      * Writes chars from a {@code char[]} to bytes on an
  3261.      * {@link OutputStream} using the specified character encoding.
  3262.      * <p>
  3263.      * Character encoding names can be found at
  3264.      * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
  3265.      * </p>
  3266.      * <p>
  3267.      * This method uses {@link String#String(char[])} and
  3268.      * {@link String#getBytes(String)}.
  3269.      * </p>
  3270.      *
  3271.      * @param data the char array to write, do not modify during output,
  3272.      * null ignored
  3273.      * @param output the {@link OutputStream} to write to
  3274.      * @param charsetName the name of the requested charset, null means platform default
  3275.      * @throws NullPointerException                         if output is null
  3276.      * @throws IOException                                  if an I/O error occurs
  3277.      * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported
  3278.      * @since 1.1
  3279.      */
  3280.     public static void write(final char[] data, final OutputStream output, final String charsetName)
  3281.             throws IOException {
  3282.         write(data, output, Charsets.toCharset(charsetName));
  3283.     }

  3284.     /**
  3285.      * Writes chars from a {@code char[]} to a {@link Writer}
  3286.      *
  3287.      * @param data the char array to write, do not modify during output,
  3288.      * null ignored
  3289.      * @param writer the {@link Writer} to write to
  3290.      * @throws NullPointerException if output is null
  3291.      * @throws IOException          if an I/O error occurs
  3292.      * @since 1.1
  3293.      */
  3294.     public static void write(final char[] data, final Writer writer) throws IOException {
  3295.         if (data != null) {
  3296.             writer.write(data);
  3297.         }
  3298.     }

  3299.     /**
  3300.      * Writes chars from a {@link CharSequence} to bytes on an
  3301.      * {@link OutputStream} using the virtual machine's {@link Charset#defaultCharset() default charset}.
  3302.      * <p>
  3303.      * This method uses {@link String#getBytes()}.
  3304.      * </p>
  3305.      *
  3306.      * @param data the {@link CharSequence} to write, null ignored
  3307.      * @param output the {@link OutputStream} to write to
  3308.      * @throws NullPointerException if output is null
  3309.      * @throws IOException          if an I/O error occurs
  3310.      * @since 2.0
  3311.      * @deprecated Use {@link #write(CharSequence, OutputStream, Charset)} instead
  3312.      */
  3313.     @Deprecated
  3314.     public static void write(final CharSequence data, final OutputStream output)
  3315.             throws IOException {
  3316.         write(data, output, Charset.defaultCharset());
  3317.     }

  3318.     /**
  3319.      * Writes chars from a {@link CharSequence} to bytes on an
  3320.      * {@link OutputStream} using the specified character encoding.
  3321.      * <p>
  3322.      * This method uses {@link String#getBytes(String)}.
  3323.      * </p>
  3324.      *
  3325.      * @param data the {@link CharSequence} to write, null ignored
  3326.      * @param output the {@link OutputStream} to write to
  3327.      * @param charset the charset to use, null means platform default
  3328.      * @throws NullPointerException if output is null
  3329.      * @throws IOException          if an I/O error occurs
  3330.      * @since 2.3
  3331.      */
  3332.     public static void write(final CharSequence data, final OutputStream output, final Charset charset)
  3333.             throws IOException {
  3334.         if (data != null) {
  3335.             write(data.toString(), output, charset);
  3336.         }
  3337.     }

  3338.     /**
  3339.      * Writes chars from a {@link CharSequence} to bytes on an
  3340.      * {@link OutputStream} using the specified character encoding.
  3341.      * <p>
  3342.      * Character encoding names can be found at
  3343.      * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
  3344.      * </p>
  3345.      * <p>
  3346.      * This method uses {@link String#getBytes(String)}.
  3347.      * </p>
  3348.      *
  3349.      * @param data the {@link CharSequence} to write, null ignored
  3350.      * @param output the {@link OutputStream} to write to
  3351.      * @param charsetName the name of the requested charset, null means platform default
  3352.      * @throws NullPointerException        if output is null
  3353.      * @throws IOException                 if an I/O error occurs
  3354.      * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported
  3355.      * @since 2.0
  3356.      */
  3357.     public static void write(final CharSequence data, final OutputStream output, final String charsetName)
  3358.             throws IOException {
  3359.         write(data, output, Charsets.toCharset(charsetName));
  3360.     }

  3361.     /**
  3362.      * Writes chars from a {@link CharSequence} to a {@link Writer}.
  3363.      *
  3364.      * @param data the {@link CharSequence} to write, null ignored
  3365.      * @param writer the {@link Writer} to write to
  3366.      * @throws NullPointerException if output is null
  3367.      * @throws IOException          if an I/O error occurs
  3368.      * @since 2.0
  3369.      */
  3370.     public static void write(final CharSequence data, final Writer writer) throws IOException {
  3371.         if (data != null) {
  3372.             write(data.toString(), writer);
  3373.         }
  3374.     }

  3375.     /**
  3376.      * Writes chars from a {@link String} to bytes on an
  3377.      * {@link OutputStream} using the virtual machine's {@link Charset#defaultCharset() default charset}.
  3378.      * <p>
  3379.      * This method uses {@link String#getBytes()}.
  3380.      * </p>
  3381.      *
  3382.      * @param data the {@link String} to write, null ignored
  3383.      * @param output the {@link OutputStream} to write to
  3384.      * @throws NullPointerException if output is null
  3385.      * @throws IOException          if an I/O error occurs
  3386.      * @since 1.1
  3387.      * @deprecated Use {@link #write(String, OutputStream, Charset)} instead
  3388.      */
  3389.     @Deprecated
  3390.     public static void write(final String data, final OutputStream output)
  3391.             throws IOException {
  3392.         write(data, output, Charset.defaultCharset());
  3393.     }

  3394.     /**
  3395.      * Writes chars from a {@link String} to bytes on an
  3396.      * {@link OutputStream} using the specified character encoding.
  3397.      * <p>
  3398.      * This method uses {@link String#getBytes(String)}.
  3399.      * </p>
  3400.      *
  3401.      * @param data the {@link String} to write, null ignored
  3402.      * @param output the {@link OutputStream} to write to
  3403.      * @param charset the charset to use, null means platform default
  3404.      * @throws NullPointerException if output is null
  3405.      * @throws IOException          if an I/O error occurs
  3406.      * @since 2.3
  3407.      */
  3408.     @SuppressWarnings("resource")
  3409.     public static void write(final String data, final OutputStream output, final Charset charset) throws IOException {
  3410.         if (data != null) {
  3411.             // Use Charset#encode(String), since calling String#getBytes(Charset) might result in
  3412.             // NegativeArraySizeException or OutOfMemoryError.
  3413.             // The underlying OutputStream should not be closed, so the channel is not closed.
  3414.             Channels.newChannel(output).write(Charsets.toCharset(charset).encode(data));
  3415.         }
  3416.     }

  3417.     /**
  3418.      * Writes chars from a {@link String} to bytes on an
  3419.      * {@link OutputStream} using the specified character encoding.
  3420.      * <p>
  3421.      * Character encoding names can be found at
  3422.      * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
  3423.      * </p>
  3424.      * <p>
  3425.      * This method uses {@link String#getBytes(String)}.
  3426.      * </p>
  3427.      *
  3428.      * @param data the {@link String} to write, null ignored
  3429.      * @param output the {@link OutputStream} to write to
  3430.      * @param charsetName the name of the requested charset, null means platform default
  3431.      * @throws NullPointerException        if output is null
  3432.      * @throws IOException                 if an I/O error occurs
  3433.      * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported
  3434.      * @since 1.1
  3435.      */
  3436.     public static void write(final String data, final OutputStream output, final String charsetName)
  3437.             throws IOException {
  3438.         write(data, output, Charsets.toCharset(charsetName));
  3439.     }

  3440.     /**
  3441.      * Writes chars from a {@link String} to a {@link Writer}.
  3442.      *
  3443.      * @param data the {@link String} to write, null ignored
  3444.      * @param writer the {@link Writer} to write to
  3445.      * @throws NullPointerException if output is null
  3446.      * @throws IOException          if an I/O error occurs
  3447.      * @since 1.1
  3448.      */
  3449.     public static void write(final String data, final Writer writer) throws IOException {
  3450.         if (data != null) {
  3451.             writer.write(data);
  3452.         }
  3453.     }

  3454.     /**
  3455.      * Writes chars from a {@link StringBuffer} to bytes on an
  3456.      * {@link OutputStream} using the default character encoding of the
  3457.      * platform.
  3458.      * <p>
  3459.      * This method uses {@link String#getBytes()}.
  3460.      * </p>
  3461.      *
  3462.      * @param data the {@link StringBuffer} to write, null ignored
  3463.      * @param output the {@link OutputStream} to write to
  3464.      * @throws NullPointerException if output is null
  3465.      * @throws IOException          if an I/O error occurs
  3466.      * @since 1.1
  3467.      * @deprecated Use {@link #write(CharSequence, OutputStream)}
  3468.      */
  3469.     @Deprecated
  3470.     public static void write(final StringBuffer data, final OutputStream output) //NOSONAR
  3471.             throws IOException {
  3472.         write(data, output, (String) null);
  3473.     }

  3474.     /**
  3475.      * Writes chars from a {@link StringBuffer} to bytes on an
  3476.      * {@link OutputStream} using the specified character encoding.
  3477.      * <p>
  3478.      * Character encoding names can be found at
  3479.      * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
  3480.      * </p>
  3481.      * <p>
  3482.      * This method uses {@link String#getBytes(String)}.
  3483.      * </p>
  3484.      *
  3485.      * @param data the {@link StringBuffer} to write, null ignored
  3486.      * @param output the {@link OutputStream} to write to
  3487.      * @param charsetName the name of the requested charset, null means platform default
  3488.      * @throws NullPointerException        if output is null
  3489.      * @throws IOException                 if an I/O error occurs
  3490.      * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported
  3491.      * @since 1.1
  3492.      * @deprecated Use {@link #write(CharSequence, OutputStream, String)}.
  3493.      */
  3494.     @Deprecated
  3495.     public static void write(final StringBuffer data, final OutputStream output, final String charsetName) //NOSONAR
  3496.         throws IOException {
  3497.         if (data != null) {
  3498.             write(data.toString(), output, Charsets.toCharset(charsetName));
  3499.         }
  3500.     }

  3501.     /**
  3502.      * Writes chars from a {@link StringBuffer} to a {@link Writer}.
  3503.      *
  3504.      * @param data the {@link StringBuffer} to write, null ignored
  3505.      * @param writer the {@link Writer} to write to
  3506.      * @throws NullPointerException if output is null
  3507.      * @throws IOException          if an I/O error occurs
  3508.      * @since 1.1
  3509.      * @deprecated Use {@link #write(CharSequence, Writer)}
  3510.      */
  3511.     @Deprecated
  3512.     public static void write(final StringBuffer data, final Writer writer) //NOSONAR
  3513.             throws IOException {
  3514.         if (data != null) {
  3515.             writer.write(data.toString());
  3516.         }
  3517.     }

  3518.     /**
  3519.      * Writes bytes from a {@code byte[]} to an {@link OutputStream} using chunked writes.
  3520.      * This is intended for writing very large byte arrays which might otherwise cause excessive
  3521.      * memory usage if the native code has to allocate a copy.
  3522.      *
  3523.      * @param data the byte array to write, do not modify during output,
  3524.      * null ignored
  3525.      * @param output the {@link OutputStream} to write to
  3526.      * @throws NullPointerException if output is null
  3527.      * @throws IOException          if an I/O error occurs
  3528.      * @since 2.5
  3529.      */
  3530.     public static void writeChunked(final byte[] data, final OutputStream output)
  3531.             throws IOException {
  3532.         if (data != null) {
  3533.             int bytes = data.length;
  3534.             int offset = 0;
  3535.             while (bytes > 0) {
  3536.                 final int chunk = Math.min(bytes, DEFAULT_BUFFER_SIZE);
  3537.                 output.write(data, offset, chunk);
  3538.                 bytes -= chunk;
  3539.                 offset += chunk;
  3540.             }
  3541.         }
  3542.     }

  3543.     /**
  3544.      * Writes chars from a {@code char[]} to a {@link Writer} using chunked writes.
  3545.      * This is intended for writing very large byte arrays which might otherwise cause excessive
  3546.      * memory usage if the native code has to allocate a copy.
  3547.      *
  3548.      * @param data the char array to write, do not modify during output,
  3549.      * null ignored
  3550.      * @param writer the {@link Writer} to write to
  3551.      * @throws NullPointerException if output is null
  3552.      * @throws IOException          if an I/O error occurs
  3553.      * @since 2.5
  3554.      */
  3555.     public static void writeChunked(final char[] data, final Writer writer) throws IOException {
  3556.         if (data != null) {
  3557.             int bytes = data.length;
  3558.             int offset = 0;
  3559.             while (bytes > 0) {
  3560.                 final int chunk = Math.min(bytes, DEFAULT_BUFFER_SIZE);
  3561.                 writer.write(data, offset, chunk);
  3562.                 bytes -= chunk;
  3563.                 offset += chunk;
  3564.             }
  3565.         }
  3566.     }

  3567.     /**
  3568.      * Writes the {@link #toString()} value of each item in a collection to
  3569.      * an {@link OutputStream} line by line, using the virtual machine's {@link Charset#defaultCharset() default charset}
  3570.      * and the specified line ending.
  3571.      *
  3572.      * @param lines the lines to write, null entries produce blank lines
  3573.      * @param lineEnding the line separator to use, null is system default
  3574.      * @param output the {@link OutputStream} to write to, not null, not closed
  3575.      * @throws NullPointerException if the output is null
  3576.      * @throws IOException          if an I/O error occurs
  3577.      * @since 1.1
  3578.      * @deprecated Use {@link #writeLines(Collection, String, OutputStream, Charset)} instead
  3579.      */
  3580.     @Deprecated
  3581.     public static void writeLines(final Collection<?> lines, final String lineEnding,
  3582.                                   final OutputStream output) throws IOException {
  3583.         writeLines(lines, lineEnding, output, Charset.defaultCharset());
  3584.     }

  3585.     /**
  3586.      * Writes the {@link #toString()} value of each item in a collection to
  3587.      * an {@link OutputStream} line by line, using the specified character
  3588.      * encoding and the specified line ending.
  3589.      * <p>
  3590.      * UTF-16 is written big-endian with no byte order mark.
  3591.      * For little-endian, use UTF-16LE. For a BOM, write it to the stream
  3592.      * before calling this method.
  3593.      * </p>
  3594.      *
  3595.      * @param lines the lines to write, null entries produce blank lines
  3596.      * @param lineEnding the line separator to use, null is system default
  3597.      * @param output the {@link OutputStream} to write to, not null, not closed
  3598.      * @param charset the charset to use, null means platform default
  3599.      * @throws NullPointerException if output is null
  3600.      * @throws IOException          if an I/O error occurs
  3601.      * @since 2.3
  3602.      */
  3603.     public static void writeLines(final Collection<?> lines, String lineEnding, final OutputStream output,
  3604.             Charset charset) throws IOException {
  3605.         if (lines == null) {
  3606.             return;
  3607.         }
  3608.         if (lineEnding == null) {
  3609.             lineEnding = System.lineSeparator();
  3610.         }
  3611.         if (StandardCharsets.UTF_16.equals(charset)) {
  3612.             // don't write a BOM
  3613.             charset = StandardCharsets.UTF_16BE;
  3614.         }
  3615.         final byte[] eolBytes = lineEnding.getBytes(charset);
  3616.         for (final Object line : lines) {
  3617.             if (line != null) {
  3618.                 write(line.toString(), output, charset);
  3619.             }
  3620.             output.write(eolBytes);
  3621.         }
  3622.     }

  3623.     /**
  3624.      * Writes the {@link #toString()} value of each item in a collection to
  3625.      * an {@link OutputStream} line by line, using the specified character
  3626.      * encoding and the specified line ending.
  3627.      * <p>
  3628.      * Character encoding names can be found at
  3629.      * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
  3630.      * </p>
  3631.      *
  3632.      * @param lines the lines to write, null entries produce blank lines
  3633.      * @param lineEnding the line separator to use, null is system default
  3634.      * @param output the {@link OutputStream} to write to, not null, not closed
  3635.      * @param charsetName the name of the requested charset, null means platform default
  3636.      * @throws NullPointerException                         if the output is null
  3637.      * @throws IOException                                  if an I/O error occurs
  3638.      * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported
  3639.      * @since 1.1
  3640.      */
  3641.     public static void writeLines(final Collection<?> lines, final String lineEnding,
  3642.                                   final OutputStream output, final String charsetName) throws IOException {
  3643.         writeLines(lines, lineEnding, output, Charsets.toCharset(charsetName));
  3644.     }

  3645.     /**
  3646.      * Writes the {@link #toString()} value of each item in a collection to
  3647.      * a {@link Writer} line by line, using the specified line ending.
  3648.      *
  3649.      * @param lines the lines to write, null entries produce blank lines
  3650.      * @param lineEnding the line separator to use, null is system default
  3651.      * @param writer the {@link Writer} to write to, not null, not closed
  3652.      * @throws NullPointerException if the input is null
  3653.      * @throws IOException          if an I/O error occurs
  3654.      * @since 1.1
  3655.      */
  3656.     public static void writeLines(final Collection<?> lines, String lineEnding,
  3657.                                   final Writer writer) throws IOException {
  3658.         if (lines == null) {
  3659.             return;
  3660.         }
  3661.         if (lineEnding == null) {
  3662.             lineEnding = System.lineSeparator();
  3663.         }
  3664.         for (final Object line : lines) {
  3665.             if (line != null) {
  3666.                 writer.write(line.toString());
  3667.             }
  3668.             writer.write(lineEnding);
  3669.         }
  3670.     }

  3671.     /**
  3672.      * Returns the given Appendable if it is already a {@link Writer}, otherwise creates a Writer wrapper around the
  3673.      * given Appendable.
  3674.      *
  3675.      * @param appendable the Appendable to wrap or return (not null)
  3676.      * @return  the given Appendable or a Writer wrapper around the given Appendable
  3677.      * @throws NullPointerException if the input parameter is null
  3678.      * @since 2.7
  3679.      */
  3680.     public static Writer writer(final Appendable appendable) {
  3681.         Objects.requireNonNull(appendable, "appendable");
  3682.         if (appendable instanceof Writer) {
  3683.             return (Writer) appendable;
  3684.         }
  3685.         if (appendable instanceof StringBuilder) {
  3686.             return new StringBuilderWriter((StringBuilder) appendable);
  3687.         }
  3688.         return new AppendableWriter<>(appendable);
  3689.     }

  3690.     /**
  3691.      * Instances should NOT be constructed in standard programming.
  3692.      *
  3693.      * @deprecated TODO Make private in 3.0.
  3694.      */
  3695.     @Deprecated
  3696.     public IOUtils() { //NOSONAR
  3697.         // empty
  3698.     }

  3699. }