< prev index next >

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

Print this page




3104      *          installed, the {@link SecurityManager#checkRead(String) checkRead}
3105      *          method is invoked to check read access to the file.
3106      */
3107     public static long copy(Path source, OutputStream out) throws IOException {
3108         // ensure not null before opening file
3109         Objects.requireNonNull(out);
3110 
3111         try (InputStream in = newInputStream(source)) {
3112             return in.transferTo(out);
3113         }
3114     }
3115 
3116     /**
3117      * The maximum size of array to allocate.
3118      * Some VMs reserve some header words in an array.
3119      * Attempts to allocate larger arrays may result in
3120      * OutOfMemoryError: Requested array size exceeds VM limit
3121      */
3122     private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;
3123 



3124     /**
3125      * Reads all the bytes from an input stream. Uses {@code initialSize} as a hint
3126      * about how many bytes the stream will have.
3127      *
3128      * @param   source
3129      *          the input stream to read from
3130      * @param   initialSize
3131      *          the initial size of the byte array to allocate
3132      *
3133      * @return  a byte array containing the bytes read from the file
3134      *
3135      * @throws  IOException
3136      *          if an I/O error occurs reading from the stream
3137      * @throws  OutOfMemoryError
3138      *          if an array of the required size cannot be allocated
3139      */
3140     private static byte[] read(InputStream source, int initialSize) throws IOException {
3141         int capacity = initialSize;
3142         byte[] buf = new byte[capacity];
3143         int nread = 0;


3186      * @throws  OutOfMemoryError
3187      *          if an array of the required size cannot be allocated, for
3188      *          example the file is larger that {@code 2GB}
3189      * @throws  SecurityException
3190      *          In the case of the default provider, and a security manager is
3191      *          installed, the {@link SecurityManager#checkRead(String) checkRead}
3192      *          method is invoked to check read access to the file.
3193      */
3194     public static byte[] readAllBytes(Path path) throws IOException {
3195         try (SeekableByteChannel sbc = Files.newByteChannel(path);
3196              InputStream in = Channels.newInputStream(sbc)) {
3197             long size = sbc.size();
3198             if (size > (long)MAX_BUFFER_SIZE)
3199                 throw new OutOfMemoryError("Required array size too large");
3200 
3201             return read(in, (int)size);
3202         }
3203     }
3204 
3205     /**











































































3206      * Read all lines from a file. This method ensures that the file is
3207      * closed when all bytes have been read or an I/O error, or other runtime
3208      * exception, is thrown. Bytes from the file are decoded into characters
3209      * using the specified charset.
3210      *
3211      * <p> This method recognizes the following as line terminators:
3212      * <ul>
3213      *   <li> <code>\u000D</code> followed by <code>\u000A</code>,
3214      *     CARRIAGE RETURN followed by LINE FEED </li>
3215      *   <li> <code>\u000A</code>, LINE FEED </li>
3216      *   <li> <code>\u000D</code>, CARRIAGE RETURN </li>
3217      * </ul>
3218      * <p> Additional Unicode line terminators may be recognized in future
3219      * releases.
3220      *
3221      * <p> Note that this method is intended for simple cases where it is
3222      * convenient to read all lines in a single operation. It is not intended
3223      * for reading in large files.
3224      *
3225      * @param   path


3437      *          if an I/O error occurs writing to or creating the file, or the
3438      *          text cannot be encoded as {@code UTF-8}
3439      * @throws  UnsupportedOperationException
3440      *          if an unsupported option is specified
3441      * @throws  SecurityException
3442      *          In the case of the default provider, and a security manager is
3443      *          installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3444      *          method is invoked to check write access to the file. The {@link
3445      *          SecurityManager#checkDelete(String) checkDelete} method is
3446      *          invoked to check delete access if the file is opened with the
3447      *          {@code DELETE_ON_CLOSE} option.
3448      *
3449      * @since 1.8
3450      */
3451     public static Path write(Path path,
3452                              Iterable<? extends CharSequence> lines,
3453                              OpenOption... options)
3454         throws IOException
3455     {
3456         return write(path, lines, StandardCharsets.UTF_8, options);








































































































3457     }
3458 
3459     // -- Stream APIs --
3460 
3461     /**
3462      * Return a lazily populated {@code Stream}, the elements of
3463      * which are the entries in the directory.  The listing is not recursive.
3464      *
3465      * <p> The elements of the stream are {@link Path} objects that are
3466      * obtained as if by {@link Path#resolve(Path) resolving} the name of the
3467      * directory entry against {@code dir}. Some file systems maintain special
3468      * links to the directory itself and the directory's parent directory.
3469      * Entries representing these links are not included.
3470      *
3471      * <p> The stream is <i>weakly consistent</i>. It is thread safe but does
3472      * not freeze the directory while iterating, so it may (or may not)
3473      * reflect updates to the directory that occur after returning from this
3474      * method.
3475      *
3476      * <p> The returned stream contains a reference to an open directory.




3104      *          installed, the {@link SecurityManager#checkRead(String) checkRead}
3105      *          method is invoked to check read access to the file.
3106      */
3107     public static long copy(Path source, OutputStream out) throws IOException {
3108         // ensure not null before opening file
3109         Objects.requireNonNull(out);
3110 
3111         try (InputStream in = newInputStream(source)) {
3112             return in.transferTo(out);
3113         }
3114     }
3115 
3116     /**
3117      * The maximum size of array to allocate.
3118      * Some VMs reserve some header words in an array.
3119      * Attempts to allocate larger arrays may result in
3120      * OutOfMemoryError: Requested array size exceeds VM limit
3121      */
3122     private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;
3123 
3124     private static final jdk.internal.misc.JavaLangAccess JLA =
3125             jdk.internal.misc.SharedSecrets.getJavaLangAccess();
3126 
3127     /**
3128      * Reads all the bytes from an input stream. Uses {@code initialSize} as a hint
3129      * about how many bytes the stream will have.
3130      *
3131      * @param   source
3132      *          the input stream to read from
3133      * @param   initialSize
3134      *          the initial size of the byte array to allocate
3135      *
3136      * @return  a byte array containing the bytes read from the file
3137      *
3138      * @throws  IOException
3139      *          if an I/O error occurs reading from the stream
3140      * @throws  OutOfMemoryError
3141      *          if an array of the required size cannot be allocated
3142      */
3143     private static byte[] read(InputStream source, int initialSize) throws IOException {
3144         int capacity = initialSize;
3145         byte[] buf = new byte[capacity];
3146         int nread = 0;


3189      * @throws  OutOfMemoryError
3190      *          if an array of the required size cannot be allocated, for
3191      *          example the file is larger that {@code 2GB}
3192      * @throws  SecurityException
3193      *          In the case of the default provider, and a security manager is
3194      *          installed, the {@link SecurityManager#checkRead(String) checkRead}
3195      *          method is invoked to check read access to the file.
3196      */
3197     public static byte[] readAllBytes(Path path) throws IOException {
3198         try (SeekableByteChannel sbc = Files.newByteChannel(path);
3199              InputStream in = Channels.newInputStream(sbc)) {
3200             long size = sbc.size();
3201             if (size > (long)MAX_BUFFER_SIZE)
3202                 throw new OutOfMemoryError("Required array size too large");
3203 
3204             return read(in, (int)size);
3205         }
3206     }
3207 
3208     /**
3209      * Reads all content from a file into a string, decoding from bytes to characters
3210      * using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.
3211      * The method ensures that the file is closed when all content have been read
3212      * or an I/O error, or other runtime exception, is thrown.
3213      *
3214      * <p> This method is equivalent to:
3215      * {@code readString(path, StandardCharsets.UTF_8) }
3216      *
3217      * @param   path the path to the file
3218      *
3219      * @return  a String containing the content read from the file
3220      *
3221      * @throws  IOException
3222      *          if an I/O error occurs reading from the file or a malformed or
3223      *          unmappable byte sequence is read
3224      * @throws  OutOfMemoryError
3225      *          if the file is extremely large, for example larger than {@code 2GB}
3226      * @throws  SecurityException
3227      *          In the case of the default provider, and a security manager is
3228      *          installed, the {@link SecurityManager#checkRead(String) checkRead}
3229      *          method is invoked to check read access to the file.
3230      *
3231      * @since 11
3232      */
3233     public static String readString(Path path) throws IOException {
3234         return readString(path, StandardCharsets.UTF_8);
3235     }
3236 
3237     /**
3238      * Reads all characters from a file into a string, decoding from bytes to characters
3239      * using the specified {@linkplain Charset charset}.
3240      * The method ensures that the file is closed when all content have been read
3241      * or an I/O error, or other runtime exception, is thrown.
3242      *
3243      * <p> This method reads all content including the line separators in the middle
3244      * and/or at the end. The resulting string will contain line separators as they
3245      * appear in the file.
3246      *
3247      * @apiNote
3248      * This method is intended for simple cases where it is appropriate and convenient
3249      * to read the content of a file into a String. It is not intended for reading
3250      * very large files.
3251      *
3252      *
3253      *
3254      * @param   path the path to the file
3255      * @param   cs the charset to use for decoding
3256      *
3257      * @return  a String containing the content read from the file
3258      *
3259      * @throws  IOException
3260      *          if an I/O error occurs reading from the file or a malformed or
3261      *          unmappable byte sequence is read
3262      * @throws  OutOfMemoryError
3263      *          if the file is extremely large, for example larger than {@code 2GB}
3264      * @throws  SecurityException
3265      *          In the case of the default provider, and a security manager is
3266      *          installed, the {@link SecurityManager#checkRead(String) checkRead}
3267      *          method is invoked to check read access to the file.
3268      *
3269      * @since 11
3270      */
3271     public static String readString(Path path, Charset cs) throws IOException {
3272         Objects.requireNonNull(path);
3273         Objects.requireNonNull(cs);
3274 
3275         byte[] ba = readAllBytes(path);
3276         try {
3277             return JLA.newStringNoRepl(ba, cs);
3278         } catch (IllegalArgumentException e) {
3279             throw new IOException(e);
3280         }
3281     }
3282 
3283     /**
3284      * Read all lines from a file. This method ensures that the file is
3285      * closed when all bytes have been read or an I/O error, or other runtime
3286      * exception, is thrown. Bytes from the file are decoded into characters
3287      * using the specified charset.
3288      *
3289      * <p> This method recognizes the following as line terminators:
3290      * <ul>
3291      *   <li> <code>\u000D</code> followed by <code>\u000A</code>,
3292      *     CARRIAGE RETURN followed by LINE FEED </li>
3293      *   <li> <code>\u000A</code>, LINE FEED </li>
3294      *   <li> <code>\u000D</code>, CARRIAGE RETURN </li>
3295      * </ul>
3296      * <p> Additional Unicode line terminators may be recognized in future
3297      * releases.
3298      *
3299      * <p> Note that this method is intended for simple cases where it is
3300      * convenient to read all lines in a single operation. It is not intended
3301      * for reading in large files.
3302      *
3303      * @param   path


3515      *          if an I/O error occurs writing to or creating the file, or the
3516      *          text cannot be encoded as {@code UTF-8}
3517      * @throws  UnsupportedOperationException
3518      *          if an unsupported option is specified
3519      * @throws  SecurityException
3520      *          In the case of the default provider, and a security manager is
3521      *          installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3522      *          method is invoked to check write access to the file. The {@link
3523      *          SecurityManager#checkDelete(String) checkDelete} method is
3524      *          invoked to check delete access if the file is opened with the
3525      *          {@code DELETE_ON_CLOSE} option.
3526      *
3527      * @since 1.8
3528      */
3529     public static Path write(Path path,
3530                              Iterable<? extends CharSequence> lines,
3531                              OpenOption... options)
3532         throws IOException
3533     {
3534         return write(path, lines, StandardCharsets.UTF_8, options);
3535     }
3536 
3537     /**
3538      * Write a {@linkplain java.lang.CharSequence CharSequence} to a file.
3539      * Characters are encoded into bytes using the
3540      * {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.
3541      *
3542      * <p> This method is equivalent to:
3543      * {@code writeString(path, test, StandardCharsets.UTF_8, options) }
3544      *
3545      * @param   path
3546      *          the path to the file
3547      * @param   csq
3548      *          the CharSequence to be written
3549      * @param   options
3550      *          options specifying how the file is opened
3551      *
3552      * @return  the path
3553      *
3554      * @throws  IllegalArgumentException
3555      *          if {@code options} contains an invalid combination of options
3556      * @throws  IOException
3557      *          if an I/O error occurs writing to or creating the file, or the
3558      *          text cannot be encoded using the specified charset
3559      * @throws  UnsupportedOperationException
3560      *          if an unsupported option is specified
3561      * @throws  SecurityException
3562      *          In the case of the default provider, and a security manager is
3563      *          installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3564      *          method is invoked to check write access to the file. The {@link
3565      *          SecurityManager#checkDelete(String) checkDelete} method is
3566      *          invoked to check delete access if the file is opened with the
3567      *          {@code DELETE_ON_CLOSE} option.
3568      *
3569      * @since 11
3570      */
3571     public static Path writeString(Path path, CharSequence csq, OpenOption... options)
3572             throws IOException
3573     {
3574         return writeString(path, csq, StandardCharsets.UTF_8, options);
3575     }
3576 
3577     /**
3578      * Write a {@linkplain java.lang.CharSequence CharSequence} to a file.
3579      * Characters are encoded into bytes using the specified
3580      * {@linkplain java.nio.charset.Charset charset}.
3581      *
3582      * <p> All characters are written as they are, including the line separators in
3583      * the char sequence. No extra characters are added.
3584      *
3585      * <p> The {@code options} parameter specifies how the file is created
3586      * or opened. If no options are present then this method works as if the
3587      * {@link StandardOpenOption#CREATE CREATE}, {@link
3588      * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING}, and {@link
3589      * StandardOpenOption#WRITE WRITE} options are present. In other words, it
3590      * opens the file for writing, creating the file if it doesn't exist, or
3591      * initially truncating an existing {@link #isRegularFile regular-file} to
3592      * a size of {@code 0}.
3593      *
3594      *
3595      * @param   path
3596      *          the path to the file
3597      * @param   csq
3598      *          the CharSequence to be written
3599      * @param   cs
3600      *          the charset to use for encoding
3601      * @param   options
3602      *          options specifying how the file is opened
3603      *
3604      * @return  the path
3605      *
3606      * @throws  IllegalArgumentException
3607      *          if {@code options} contains an invalid combination of options
3608      * @throws  IOException
3609      *          if an I/O error occurs writing to or creating the file, or the
3610      *          text cannot be encoded using the specified charset
3611      * @throws  UnsupportedOperationException
3612      *          if an unsupported option is specified
3613      * @throws  SecurityException
3614      *          In the case of the default provider, and a security manager is
3615      *          installed, the {@link SecurityManager#checkWrite(String) checkWrite}
3616      *          method is invoked to check write access to the file. The {@link
3617      *          SecurityManager#checkDelete(String) checkDelete} method is
3618      *          invoked to check delete access if the file is opened with the
3619      *          {@code DELETE_ON_CLOSE} option.
3620      *
3621      * @since 11
3622      */
3623     public static Path writeString(Path path, CharSequence csq, Charset cs, OpenOption... options)
3624             throws IOException
3625     {
3626         // ensure the text is not null before opening file
3627         Objects.requireNonNull(path);
3628         Objects.requireNonNull(csq);
3629         Objects.requireNonNull(cs);
3630 
3631         try {
3632             byte[] bytes = JLA.getBytesNoRepl(String.valueOf(csq), cs);
3633             write(path, bytes, options);
3634         } catch (IllegalArgumentException e) {
3635             throw new IOException(e);
3636         }
3637 
3638         return path;
3639     }
3640 
3641     // -- Stream APIs --
3642 
3643     /**
3644      * Return a lazily populated {@code Stream}, the elements of
3645      * which are the entries in the directory.  The listing is not recursive.
3646      *
3647      * <p> The elements of the stream are {@link Path} objects that are
3648      * obtained as if by {@link Path#resolve(Path) resolving} the name of the
3649      * directory entry against {@code dir}. Some file systems maintain special
3650      * links to the directory itself and the directory's parent directory.
3651      * Entries representing these links are not included.
3652      *
3653      * <p> The stream is <i>weakly consistent</i>. It is thread safe but does
3654      * not freeze the directory while iterating, so it may (or may not)
3655      * reflect updates to the directory that occur after returning from this
3656      * method.
3657      *
3658      * <p> The returned stream contains a reference to an open directory.


< prev index next >