IOUtils.java

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

  20. import java.io.ByteArrayOutputStream;
  21. import java.io.Closeable;
  22. import java.io.EOFException;
  23. import java.io.File;
  24. import java.io.IOException;
  25. import java.io.InputStream;
  26. import java.io.OutputStream;
  27. import java.nio.ByteBuffer;
  28. import java.nio.channels.ReadableByteChannel;
  29. import java.nio.file.Files;
  30. import java.nio.file.LinkOption;

  31. import org.apache.commons.io.FileUtils;

  32. /**
  33.  * Utility functions.
  34.  *
  35.  * @Immutable (has mutable data but it is write-only).
  36.  */
  37. public final class IOUtils {

  38.     /**
  39.      * Empty array of type {@link LinkOption}.
  40.      *
  41.      * @since 1.21
  42.      */
  43.     public static final LinkOption[] EMPTY_LINK_OPTIONS = {};

  44.     /**
  45.      * Closes the given Closeable and swallows any IOException that may occur.
  46.      *
  47.      * @param c Closeable to close, can be null
  48.      * @since 1.7
  49.      * @deprecated Use {@link org.apache.commons.io.IOUtils#closeQuietly(Closeable)}.
  50.      */
  51.     @Deprecated
  52.     public static void closeQuietly(final Closeable c) {
  53.         org.apache.commons.io.IOUtils.closeQuietly(c);
  54.     }

  55.     /**
  56.      * Copies the source file to the given output stream.
  57.      *
  58.      * @param sourceFile   The file to read.
  59.      * @param outputStream The output stream to write.
  60.      * @throws IOException if an I/O error occurs when reading or writing.
  61.      * @since 1.21
  62.      * @deprecated Use {@link FileUtils#copyFile(File, OutputStream)}.
  63.      */
  64.     @Deprecated
  65.     public static void copy(final File sourceFile, final OutputStream outputStream) throws IOException {
  66.         FileUtils.copyFile(sourceFile, outputStream);
  67.     }

  68.     /**
  69.      * Copies the content of a InputStream into an OutputStream. Uses a default buffer size of 8024 bytes.
  70.      *
  71.      * @param input  the InputStream to copy
  72.      * @param output the target, may be null to simulate output to dev/null on Linux and NUL on Windows
  73.      * @return the number of bytes copied
  74.      * @throws IOException if an error occurs
  75.      * @deprecated Use {@link org.apache.commons.io.IOUtils#copy(InputStream, OutputStream)}.
  76.      */
  77.     @Deprecated
  78.     public static long copy(final InputStream input, final OutputStream output) throws IOException {
  79.         return org.apache.commons.io.IOUtils.copy(input, output);
  80.     }

  81.     /**
  82.      * Copies the content of a InputStream into an OutputStream
  83.      *
  84.      * @param input      the InputStream to copy
  85.      * @param output     the target, may be null to simulate output to dev/null on Linux and NUL on Windows
  86.      * @param bufferSize the buffer size to use, must be bigger than 0
  87.      * @return the number of bytes copied
  88.      * @throws IOException              if an error occurs
  89.      * @throws IllegalArgumentException if bufferSize is smaller than or equal to 0
  90.      * @deprecated Use {@link org.apache.commons.io.IOUtils#copy(InputStream, OutputStream, int)}.
  91.      */
  92.     @Deprecated
  93.     public static long copy(final InputStream input, final OutputStream output, final int bufferSize) throws IOException {
  94.         return org.apache.commons.io.IOUtils.copy(input, output, bufferSize);
  95.     }

  96.     /**
  97.      * Copies part of the content of a InputStream into an OutputStream. Uses a default buffer size of 8024 bytes.
  98.      *
  99.      * @param input  the InputStream to copy
  100.      * @param output the target Stream
  101.      * @param len    maximum amount of bytes to copy
  102.      * @return the number of bytes copied
  103.      * @throws IOException if an error occurs
  104.      * @since 1.21
  105.      * @deprecated Use {@link org.apache.commons.io.IOUtils#copyLarge(InputStream, OutputStream, long, long)}.
  106.      */
  107.     @Deprecated
  108.     public static long copyRange(final InputStream input, final long len, final OutputStream output) throws IOException {
  109.         return org.apache.commons.io.IOUtils.copyLarge(input, output, 0, len);
  110.     }

  111.     /**
  112.      * Copies part of the content of a InputStream into an OutputStream
  113.      *
  114.      * @param input      the InputStream to copy
  115.      * @param length        maximum amount of bytes to copy
  116.      * @param output     the target, may be null to simulate output to dev/null on Linux and NUL on Windows
  117.      * @param bufferSize the buffer size to use, must be bigger than 0
  118.      * @return the number of bytes copied
  119.      * @throws IOException              if an error occurs
  120.      * @throws IllegalArgumentException if bufferSize is smaller than or equal to 0
  121.      * @since 1.21
  122.      * @deprecated No longer used.
  123.      */
  124.     @Deprecated
  125.     public static long copyRange(final InputStream input, final long length, final OutputStream output, final int bufferSize) throws IOException {
  126.         if (bufferSize < 1) {
  127.             throw new IllegalArgumentException("bufferSize must be bigger than 0");
  128.         }
  129.         final byte[] buffer = new byte[(int) Math.min(bufferSize, Math.max(0, length))];
  130.         int n = 0;
  131.         long count = 0;
  132.         while (count < length && -1 != (n = input.read(buffer, 0, (int) Math.min(length - count, buffer.length)))) {
  133.             if (output != null) {
  134.                 output.write(buffer, 0, n);
  135.             }
  136.             count += n;
  137.         }
  138.         return count;
  139.     }

  140.     /**
  141.      * Reads as much from the file as possible to fill the given array.
  142.      * <p>
  143.      * This method may invoke read repeatedly to fill the array and only read less bytes than the length of the array if the end of the stream has been reached.
  144.      * </p>
  145.      *
  146.      * @param file  file to read
  147.      * @param array buffer to fill
  148.      * @return the number of bytes actually read
  149.      * @throws IOException on error
  150.      * @since 1.20
  151.      * @deprecated Use {@link Files#readAllBytes(java.nio.file.Path)}.
  152.      */
  153.     @Deprecated
  154.     public static int read(final File file, final byte[] array) throws IOException {
  155.         try (InputStream inputStream = Files.newInputStream(file.toPath())) {
  156.             return readFully(inputStream, array, 0, array.length);
  157.         }
  158.     }

  159.     /**
  160.      * Reads as much from input as possible to fill the given array.
  161.      * <p>
  162.      * This method may invoke read repeatedly to fill the array and only read less bytes than the length of the array if the end of the stream has been reached.
  163.      * </p>
  164.      *
  165.      * @param input stream to read from
  166.      * @param array buffer to fill
  167.      * @return the number of bytes actually read
  168.      * @throws IOException on error
  169.      */
  170.     public static int readFully(final InputStream input, final byte[] array) throws IOException {
  171.         return readFully(input, array, 0, array.length);
  172.     }

  173.     /**
  174.      * Reads as much from input as possible to fill the given array with the given amount of bytes.
  175.      * <p>
  176.      * This method may invoke read repeatedly to read the bytes and only read less bytes than the requested length if the end of the stream has been reached.
  177.      * </p>
  178.      *
  179.      * @param input  stream to read from
  180.      * @param array  buffer to fill
  181.      * @param offset offset into the buffer to start filling at
  182.      * @param length    of bytes to read
  183.      * @return the number of bytes actually read
  184.      * @throws IOException if an I/O error has occurred
  185.      */
  186.     public static int readFully(final InputStream input, final byte[] array, final int offset, final int length) throws IOException {
  187.         if (length < 0 || offset < 0 || length + offset > array.length || length + offset < 0) {
  188.             throw new IndexOutOfBoundsException();
  189.         }
  190.         return org.apache.commons.io.IOUtils.read(input, array, offset, length);
  191.     }

  192.     /**
  193.      * Reads {@code b.remaining()} bytes from the given channel starting at the current channel's position.
  194.      * <p>
  195.      * This method reads repeatedly from the channel until the requested number of bytes are read. This method blocks until the requested number of bytes are
  196.      * read, the end of the channel is detected, or an exception is thrown.
  197.      * </p>
  198.      *
  199.      * @param channel    the channel to read from
  200.      * @param byteBuffer the buffer into which the data is read.
  201.      * @throws IOException  if an I/O error occurs.
  202.      * @throws EOFException if the channel reaches the end before reading all the bytes.
  203.      */
  204.     public static void readFully(final ReadableByteChannel channel, final ByteBuffer byteBuffer) throws IOException {
  205.         final int expectedLength = byteBuffer.remaining();
  206.         final int read = org.apache.commons.io.IOUtils.read(channel, byteBuffer);
  207.         if (read < expectedLength) {
  208.             throw new EOFException();
  209.         }
  210.     }

  211.     /**
  212.      * Gets part of the contents of an {@code InputStream} as a {@code byte[]}.
  213.      *
  214.      * @param input the {@code InputStream} to read from
  215.      * @param length   maximum amount of bytes to copy
  216.      * @return the requested byte array
  217.      * @throws NullPointerException if the input is null
  218.      * @throws IOException          if an I/O error occurs
  219.      * @since 1.21
  220.      */
  221.     public static byte[] readRange(final InputStream input, final int length) throws IOException {
  222.         final ByteArrayOutputStream output = new ByteArrayOutputStream();
  223.         org.apache.commons.io.IOUtils.copyLarge(input, output, 0, length);
  224.         return output.toByteArray();
  225.     }

  226.     /**
  227.      * Gets part of the contents of an {@code ReadableByteChannel} as a {@code byte[]}.
  228.      *
  229.      * @param input the {@code ReadableByteChannel} to read from
  230.      * @param length   maximum amount of bytes to copy
  231.      * @return the requested byte array
  232.      * @throws NullPointerException if the input is null
  233.      * @throws IOException          if an I/O error occurs
  234.      * @since 1.21
  235.      */
  236.     public static byte[] readRange(final ReadableByteChannel input, final int length) throws IOException {
  237.         final ByteArrayOutputStream output = new ByteArrayOutputStream();
  238.         final ByteBuffer b = ByteBuffer.allocate(Math.min(length, org.apache.commons.io.IOUtils.DEFAULT_BUFFER_SIZE));
  239.         int read = 0;
  240.         while (read < length) {
  241.             // Make sure we never read more than len bytes
  242.             b.limit(Math.min(length - read, b.capacity()));
  243.             final int readCount = input.read(b);
  244.             if (readCount <= 0) {
  245.                 break;
  246.             }
  247.             output.write(b.array(), 0, readCount);
  248.             b.rewind();
  249.             read += readCount;
  250.         }
  251.         return output.toByteArray();
  252.     }

  253.     /**
  254.      * Skips bytes from an input byte stream.
  255.      * <p>
  256.      * This method will only skip less than the requested number of bytes if the end of the input stream has been reached.
  257.      * </p>
  258.      *
  259.      * @param input     stream to skip bytes in
  260.      * @param toSkip the number of bytes to skip
  261.      * @return the number of bytes actually skipped
  262.      * @throws IOException on error
  263.      */
  264.     public static long skip(final InputStream input, final long toSkip) throws IOException {
  265.         return org.apache.commons.io.IOUtils.skip(input, toSkip, org.apache.commons.io.IOUtils::byteArray);
  266.     }

  267.     /**
  268.      * Gets the contents of an {@code InputStream} as a {@code byte[]}.
  269.      * <p>
  270.      * This method buffers the input internally, so there is no need to use a {@code BufferedInputStream}.
  271.      * </p>
  272.      *
  273.      * @param input the {@code InputStream} to read from
  274.      * @return the requested byte array
  275.      * @throws NullPointerException if the input is null
  276.      * @throws IOException          if an I/O error occurs
  277.      * @since 1.5
  278.      * @deprecated Use {@link org.apache.commons.io.IOUtils#toByteArray(InputStream)}.
  279.      */
  280.     @Deprecated
  281.     public static byte[] toByteArray(final InputStream input) throws IOException {
  282.         return org.apache.commons.io.IOUtils.toByteArray(input);
  283.     }

  284.     /** Private constructor to prevent instantiation of this utility class. */
  285.     private IOUtils() {
  286.     }

  287. }