src/share/classes/java/nio/file/Files.java

Print this page




   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.nio.file;
  27 
  28 import java.nio.ByteBuffer;
  29 import java.nio.file.attribute.*;
  30 import java.nio.file.spi.FileSystemProvider;
  31 import java.nio.file.spi.FileTypeDetector;

  32 import java.nio.channels.FileChannel;
  33 import java.nio.channels.SeekableByteChannel;
  34 import java.io.Closeable;
  35 import java.io.InputStream;
  36 import java.io.OutputStream;
  37 import java.io.Reader;
  38 import java.io.Writer;
  39 import java.io.BufferedReader;
  40 import java.io.BufferedWriter;
  41 import java.io.InputStreamReader;
  42 import java.io.OutputStreamWriter;
  43 import java.io.IOException;
  44 import java.io.UncheckedIOException;
  45 import java.util.*;
  46 import java.util.function.BiPredicate;
  47 import java.util.stream.CloseableStream;
  48 import java.util.stream.DelegatingStream;
  49 import java.util.stream.Stream;
  50 import java.util.stream.StreamSupport;
  51 import java.security.AccessController;


2948      *
2949      * @return  the number of bytes read or written
2950      *
2951      * @throws  IOException
2952      *          if an I/O error occurs when reading or writing
2953      * @throws  SecurityException
2954      *          In the case of the default provider, and a security manager is
2955      *          installed, the {@link SecurityManager#checkRead(String) checkRead}
2956      *          method is invoked to check read access to the file.
2957      */
2958     public static long copy(Path source, OutputStream out) throws IOException {
2959         // ensure not null before opening file
2960         Objects.requireNonNull(out);
2961 
2962         try (InputStream in = newInputStream(source)) {
2963             return copy(in, out);
2964         }
2965     }
2966 
2967     /**
2968      * Read all the bytes from a file. The method ensures that the file is
























































2969      * closed when all bytes have been read or an I/O error, or other runtime
2970      * exception, is thrown.
2971      *
2972      * <p> Note that this method is intended for simple cases where it is
2973      * convenient to read all bytes into a byte array. It is not intended for
2974      * reading in large files.
2975      *
2976      * @param   path
2977      *          the path to the file
2978      *
2979      * @return  a byte array containing the bytes read from the file
2980      *
2981      * @throws  IOException
2982      *          if an I/O error occurs reading from the stream
2983      * @throws  OutOfMemoryError
2984      *          if an array of the required size cannot be allocated, for
2985      *          example the file is larger that {@code 2GB}
2986      * @throws  SecurityException
2987      *          In the case of the default provider, and a security manager is
2988      *          installed, the {@link SecurityManager#checkRead(String) checkRead}
2989      *          method is invoked to check read access to the file.
2990      */
2991     public static byte[] readAllBytes(Path path) throws IOException {
2992         try (FileChannel fc = FileChannel.open(path)) {

2993             long size = fc.size();
2994             if (size > (long)Integer.MAX_VALUE)
2995                 throw new OutOfMemoryError("Required array size too large");
2996 
2997             byte[] arr = new byte[(int)size];
2998             ByteBuffer bb = ByteBuffer.wrap(arr);
2999             while (bb.hasRemaining()) {
3000                 if (fc.read(bb) < 0) {
3001                     // truncated
3002                     break;
3003                 }
3004             }
3005 
3006             int nread = bb.position();
3007             return (nread == size) ? arr : Arrays.copyOf(arr, nread);
3008         }
3009     }
3010 
3011     /**
3012      * Read all lines from a file. This method ensures that the file is
3013      * closed when all bytes have been read or an I/O error, or other runtime
3014      * exception, is thrown. Bytes from the file are decoded into characters
3015      * using the specified charset.
3016      *
3017      * <p> This method recognizes the following as line terminators:
3018      * <ul>
3019      *   <li> <code>&#92;u000D</code> followed by <code>&#92;u000A</code>,
3020      *     CARRIAGE RETURN followed by LINE FEED </li>
3021      *   <li> <code>&#92;u000A</code>, LINE FEED </li>
3022      *   <li> <code>&#92;u000D</code>, CARRIAGE RETURN </li>
3023      * </ul>
3024      * <p> Additional Unicode line terminators may be recognized in future
3025      * releases.
3026      *
3027      * <p> Note that this method is intended for simple cases where it is




   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.nio.file;
  27 

  28 import java.nio.file.attribute.*;
  29 import java.nio.file.spi.FileSystemProvider;
  30 import java.nio.file.spi.FileTypeDetector;
  31 import java.nio.channels.Channels;
  32 import java.nio.channels.FileChannel;
  33 import java.nio.channels.SeekableByteChannel;
  34 import java.io.Closeable;
  35 import java.io.InputStream;
  36 import java.io.OutputStream;
  37 import java.io.Reader;
  38 import java.io.Writer;
  39 import java.io.BufferedReader;
  40 import java.io.BufferedWriter;
  41 import java.io.InputStreamReader;
  42 import java.io.OutputStreamWriter;
  43 import java.io.IOException;
  44 import java.io.UncheckedIOException;
  45 import java.util.*;
  46 import java.util.function.BiPredicate;
  47 import java.util.stream.CloseableStream;
  48 import java.util.stream.DelegatingStream;
  49 import java.util.stream.Stream;
  50 import java.util.stream.StreamSupport;
  51 import java.security.AccessController;


2948      *
2949      * @return  the number of bytes read or written
2950      *
2951      * @throws  IOException
2952      *          if an I/O error occurs when reading or writing
2953      * @throws  SecurityException
2954      *          In the case of the default provider, and a security manager is
2955      *          installed, the {@link SecurityManager#checkRead(String) checkRead}
2956      *          method is invoked to check read access to the file.
2957      */
2958     public static long copy(Path source, OutputStream out) throws IOException {
2959         // ensure not null before opening file
2960         Objects.requireNonNull(out);
2961 
2962         try (InputStream in = newInputStream(source)) {
2963             return copy(in, out);
2964         }
2965     }
2966 
2967     /**
2968      * The maximum size of array to allocate.
2969      * Some VMs reserve some header words in an array.
2970      * Attempts to allocate larger arrays may result in
2971      * OutOfMemoryError: Requested array size exceeds VM limit
2972      */
2973     private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;
2974 
2975     /**
2976      * Reads all the bytes from an input stream. Uses {@code initialSize} as a hint
2977      * about how many bytes the stream will have.
2978      *
2979      * @param   source
2980      *          the input stream to read from
2981      * @param   initialSize
2982      *          the initial size of the byte array to allocate
2983      *
2984      * @return  a byte array containing the bytes read from the file
2985      *
2986      * @throws  IOException
2987      *          if an I/O error occurs reading from the stream
2988      * @throws  OutOfMemoryError
2989      *          if an array of the required size cannot be allocated
2990      */
2991     private static byte[] read(InputStream source, int initialSize)
2992             throws IOException
2993     {
2994         int capacity = initialSize;
2995         byte[] buf = new byte[capacity];
2996         int nread = 0;
2997         int n;
2998         for (;;) {
2999             // read to EOF which may read more or less than initialSize (eg: file
3000             // is truncated while we are reading)
3001             while ((n = source.read(buf, nread, capacity - nread)) > 0)
3002                 nread += n;
3003 
3004             // if last call to source.read() returned -1, we are done
3005             // otherwise, try to read one more byte; if that failed we're done too
3006             if (n < 0 || (n = source.read()) < 0)
3007                 break;
3008 
3009             // one more byte was read; need to allocate a larger buffer
3010             if (capacity <= MAX_BUFFER_SIZE - capacity) {
3011                 capacity = Math.max(capacity << 1, BUFFER_SIZE);
3012             } else {
3013                 if (capacity == MAX_BUFFER_SIZE)
3014                     throw new OutOfMemoryError("Required array size too large");
3015                 capacity = MAX_BUFFER_SIZE;
3016             }
3017             buf = Arrays.copyOf(buf, capacity);
3018             buf[nread++] = (byte)n;
3019         }
3020         return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);
3021     }
3022 
3023     /**
3024      * Reads all the bytes from a file. The method ensures that the file is
3025      * closed when all bytes have been read or an I/O error, or other runtime
3026      * exception, is thrown.
3027      *
3028      * <p> Note that this method is intended for simple cases where it is
3029      * convenient to read all bytes into a byte array. It is not intended for
3030      * reading in large files.
3031      *
3032      * @param   path
3033      *          the path to the file
3034      *
3035      * @return  a byte array containing the bytes read from the file
3036      *
3037      * @throws  IOException
3038      *          if an I/O error occurs reading from the stream
3039      * @throws  OutOfMemoryError
3040      *          if an array of the required size cannot be allocated, for
3041      *          example the file is larger that {@code 2GB}
3042      * @throws  SecurityException
3043      *          In the case of the default provider, and a security manager is
3044      *          installed, the {@link SecurityManager#checkRead(String) checkRead}
3045      *          method is invoked to check read access to the file.
3046      */
3047     public static byte[] readAllBytes(Path path) throws IOException {
3048         try (FileChannel fc = FileChannel.open(path);
3049              InputStream is = Channels.newInputStream(fc)) {
3050             long size = fc.size();
3051             if (size > (long)MAX_BUFFER_SIZE)
3052                 throw new OutOfMemoryError("Required array size too large");
3053 
3054             return read(is, (int)size);










3055         }
3056     }
3057 
3058     /**
3059      * Read all lines from a file. This method ensures that the file is
3060      * closed when all bytes have been read or an I/O error, or other runtime
3061      * exception, is thrown. Bytes from the file are decoded into characters
3062      * using the specified charset.
3063      *
3064      * <p> This method recognizes the following as line terminators:
3065      * <ul>
3066      *   <li> <code>&#92;u000D</code> followed by <code>&#92;u000A</code>,
3067      *     CARRIAGE RETURN followed by LINE FEED </li>
3068      *   <li> <code>&#92;u000A</code>, LINE FEED </li>
3069      *   <li> <code>&#92;u000D</code>, CARRIAGE RETURN </li>
3070      * </ul>
3071      * <p> Additional Unicode line terminators may be recognized in future
3072      * releases.
3073      *
3074      * <p> Note that this method is intended for simple cases where it is