< prev index next >

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

Print this page
rev 54801 : [mq]: 8223593-Refactor-code-for-reallocating-storage


  60 import java.nio.file.spi.FileTypeDetector;
  61 import java.security.AccessController;
  62 import java.security.PrivilegedAction;
  63 import java.util.ArrayList;
  64 import java.util.Arrays;
  65 import java.util.Collections;
  66 import java.util.EnumSet;
  67 import java.util.HashSet;
  68 import java.util.Iterator;
  69 import java.util.List;
  70 import java.util.Map;
  71 import java.util.Objects;
  72 import java.util.ServiceLoader;
  73 import java.util.Set;
  74 import java.util.Spliterator;
  75 import java.util.Spliterators;
  76 import java.util.function.BiPredicate;
  77 import java.util.stream.Stream;
  78 import java.util.stream.StreamSupport;
  79 

  80 import sun.nio.ch.FileChannelImpl;
  81 import sun.nio.fs.AbstractFileSystemProvider;
  82 
  83 /**
  84  * This class consists exclusively of static methods that operate on files,
  85  * directories, or other types of files.
  86  *
  87  * <p> In most cases, the methods defined here will delegate to the associated
  88  * file system provider to perform the file operations.
  89  *
  90  * @since 1.7
  91  */
  92 
  93 public final class Files {
  94     // buffer size used for reading and writing
  95     private static final int BUFFER_SIZE = 8192;
  96 
  97     private Files() { }
  98 
  99     /**


3179      *          the output stream to write to
3180      *
3181      * @return  the number of bytes read or written
3182      *
3183      * @throws  IOException
3184      *          if an I/O error occurs when reading or writing
3185      * @throws  SecurityException
3186      *          In the case of the default provider, and a security manager is
3187      *          installed, the {@link SecurityManager#checkRead(String) checkRead}
3188      *          method is invoked to check read access to the file.
3189      */
3190     public static long copy(Path source, OutputStream out) throws IOException {
3191         // ensure not null before opening file
3192         Objects.requireNonNull(out);
3193 
3194         try (InputStream in = newInputStream(source)) {
3195             return in.transferTo(out);
3196         }
3197     }
3198 
3199     /**
3200      * The maximum size of array to allocate.
3201      * Some VMs reserve some header words in an array.
3202      * Attempts to allocate larger arrays may result in
3203      * OutOfMemoryError: Requested array size exceeds VM limit
3204      */
3205     private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;
3206 
3207     private static final jdk.internal.access.JavaLangAccess JLA =
3208             jdk.internal.access.SharedSecrets.getJavaLangAccess();
3209 
3210     /**
3211      * Reads all the bytes from an input stream. Uses {@code initialSize} as a hint
3212      * about how many bytes the stream will have.
3213      *
3214      * @param   source
3215      *          the input stream to read from
3216      * @param   initialSize
3217      *          the initial size of the byte array to allocate
3218      *
3219      * @return  a byte array containing the bytes read from the file
3220      *
3221      * @throws  IOException
3222      *          if an I/O error occurs reading from the stream
3223      * @throws  OutOfMemoryError
3224      *          if an array of the required size cannot be allocated
3225      */
3226     private static byte[] read(InputStream source, int initialSize) throws IOException {
3227         int capacity = initialSize;
3228         byte[] buf = new byte[capacity];
3229         int nread = 0;
3230         int n;
3231         for (;;) {
3232             // read to EOF which may read more or less than initialSize (eg: file
3233             // is truncated while we are reading)
3234             while ((n = source.read(buf, nread, capacity - nread)) > 0)
3235                 nread += n;
3236 
3237             // if last call to source.read() returned -1, we are done
3238             // otherwise, try to read one more byte; if that failed we're done too
3239             if (n < 0 || (n = source.read()) < 0)
3240                 break;
3241 
3242             // one more byte was read; need to allocate a larger buffer
3243             if (capacity <= MAX_BUFFER_SIZE - capacity) {
3244                 capacity = Math.max(capacity << 1, BUFFER_SIZE);
3245             } else {
3246                 if (capacity == MAX_BUFFER_SIZE)
3247                     throw new OutOfMemoryError("Required array size too large");
3248                 capacity = MAX_BUFFER_SIZE;
3249             }
3250             buf = Arrays.copyOf(buf, capacity);
3251             buf[nread++] = (byte)n;
3252         }
3253         return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);
3254     }
3255 
3256     /**
3257      * Reads all the bytes from a file. The method ensures that the file is
3258      * closed when all bytes have been read or an I/O error, or other runtime
3259      * exception, is thrown.
3260      *
3261      * <p> Note that this method is intended for simple cases where it is
3262      * convenient to read all bytes into a byte array. It is not intended for
3263      * reading in large files.
3264      *
3265      * @param   path
3266      *          the path to the file
3267      *
3268      * @return  a byte array containing the bytes read from the file
3269      *
3270      * @throws  IOException
3271      *          if an I/O error occurs reading from the stream
3272      * @throws  OutOfMemoryError
3273      *          if an array of the required size cannot be allocated, for
3274      *          example the file is larger that {@code 2GB}
3275      * @throws  SecurityException
3276      *          In the case of the default provider, and a security manager is
3277      *          installed, the {@link SecurityManager#checkRead(String) checkRead}
3278      *          method is invoked to check read access to the file.
3279      */
3280     public static byte[] readAllBytes(Path path) throws IOException {
3281         try (SeekableByteChannel sbc = Files.newByteChannel(path);
3282              InputStream in = Channels.newInputStream(sbc)) {
3283             if (sbc instanceof FileChannelImpl)
3284                 ((FileChannelImpl) sbc).setUninterruptible();
3285             long size = sbc.size();
3286             if (size > (long) MAX_BUFFER_SIZE)
3287                 throw new OutOfMemoryError("Required array size too large");
3288             return read(in, (int)size);
3289         }
3290     }
3291 
3292     /**
3293      * Reads all content from a file into a string, decoding from bytes to characters
3294      * using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.
3295      * The method ensures that the file is closed when all content have been read
3296      * or an I/O error, or other runtime exception, is thrown.
3297      *
3298      * <p> This method is equivalent to:
3299      * {@code readString(path, StandardCharsets.UTF_8) }
3300      *
3301      * @param   path the path to the file
3302      *
3303      * @return  a String containing the content read from the file
3304      *
3305      * @throws  IOException
3306      *          if an I/O error occurs reading from the file or a malformed or




  60 import java.nio.file.spi.FileTypeDetector;
  61 import java.security.AccessController;
  62 import java.security.PrivilegedAction;
  63 import java.util.ArrayList;
  64 import java.util.Arrays;
  65 import java.util.Collections;
  66 import java.util.EnumSet;
  67 import java.util.HashSet;
  68 import java.util.Iterator;
  69 import java.util.List;
  70 import java.util.Map;
  71 import java.util.Objects;
  72 import java.util.ServiceLoader;
  73 import java.util.Set;
  74 import java.util.Spliterator;
  75 import java.util.Spliterators;
  76 import java.util.function.BiPredicate;
  77 import java.util.stream.Stream;
  78 import java.util.stream.StreamSupport;
  79 
  80 import jdk.internal.util.ArraysSupport;
  81 import sun.nio.ch.FileChannelImpl;
  82 import sun.nio.fs.AbstractFileSystemProvider;
  83 
  84 /**
  85  * This class consists exclusively of static methods that operate on files,
  86  * directories, or other types of files.
  87  *
  88  * <p> In most cases, the methods defined here will delegate to the associated
  89  * file system provider to perform the file operations.
  90  *
  91  * @since 1.7
  92  */
  93 
  94 public final class Files {
  95     // buffer size used for reading and writing
  96     private static final int BUFFER_SIZE = 8192;
  97 
  98     private Files() { }
  99 
 100     /**


3180      *          the output stream to write to
3181      *
3182      * @return  the number of bytes read or written
3183      *
3184      * @throws  IOException
3185      *          if an I/O error occurs when reading or writing
3186      * @throws  SecurityException
3187      *          In the case of the default provider, and a security manager is
3188      *          installed, the {@link SecurityManager#checkRead(String) checkRead}
3189      *          method is invoked to check read access to the file.
3190      */
3191     public static long copy(Path source, OutputStream out) throws IOException {
3192         // ensure not null before opening file
3193         Objects.requireNonNull(out);
3194 
3195         try (InputStream in = newInputStream(source)) {
3196             return in.transferTo(out);
3197         }
3198     }
3199 








3200     private static final jdk.internal.access.JavaLangAccess JLA =
3201             jdk.internal.access.SharedSecrets.getJavaLangAccess();
3202 
3203     /**
3204      * Reads all the bytes from an input stream. Uses {@code initialSize} as a hint
3205      * about how many bytes the stream will have.
3206      *
3207      * @param   source
3208      *          the input stream to read from
3209      * @param   initialSize
3210      *          the initial size of the byte array to allocate
3211      *
3212      * @return  a byte array containing the bytes read from the file
3213      *
3214      * @throws  IOException
3215      *          if an I/O error occurs reading from the stream
3216      * @throws  OutOfMemoryError
3217      *          if an array of the required size cannot be allocated
3218      */
3219     private static byte[] read(InputStream source, int initialSize) throws IOException {
3220         int capacity = initialSize;
3221         byte[] buf = new byte[capacity];
3222         int nread = 0;
3223         int n;
3224         for (;;) {
3225             // read to EOF which may read more or less than initialSize (eg: file
3226             // is truncated while we are reading)
3227             while ((n = source.read(buf, nread, capacity - nread)) > 0)
3228                 nread += n;
3229 
3230             // if last call to source.read() returned -1, we are done
3231             // otherwise, try to read one more byte; if that failed we're done too
3232             if (n < 0 || (n = source.read()) < 0)
3233                 break;
3234 
3235             // one more byte was read; need to allocate a larger buffer
3236             capacity = Math.max(ArraysSupport.newCapacity(capacity, 1, capacity),
3237                                 BUFFER_SIZE);





3238             buf = Arrays.copyOf(buf, capacity);
3239             buf[nread++] = (byte)n;
3240         }
3241         return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);
3242     }
3243 
3244     /**
3245      * Reads all the bytes from a file. The method ensures that the file is
3246      * closed when all bytes have been read or an I/O error, or other runtime
3247      * exception, is thrown.
3248      *
3249      * <p> Note that this method is intended for simple cases where it is
3250      * convenient to read all bytes into a byte array. It is not intended for
3251      * reading in large files.
3252      *
3253      * @param   path
3254      *          the path to the file
3255      *
3256      * @return  a byte array containing the bytes read from the file
3257      *
3258      * @throws  IOException
3259      *          if an I/O error occurs reading from the stream
3260      * @throws  OutOfMemoryError
3261      *          if an array of the required size cannot be allocated, for
3262      *          example the file is larger that {@code 2GB}
3263      * @throws  SecurityException
3264      *          In the case of the default provider, and a security manager is
3265      *          installed, the {@link SecurityManager#checkRead(String) checkRead}
3266      *          method is invoked to check read access to the file.
3267      */
3268     public static byte[] readAllBytes(Path path) throws IOException {
3269         try (SeekableByteChannel sbc = Files.newByteChannel(path);
3270              InputStream in = Channels.newInputStream(sbc)) {
3271             if (sbc instanceof FileChannelImpl)
3272                 ((FileChannelImpl) sbc).setUninterruptible();
3273             long size = sbc.size();
3274             if (size > (long) Integer.MAX_VALUE)
3275                 throw new OutOfMemoryError("Required array size too large");
3276             return read(in, (int)size);
3277         }
3278     }
3279 
3280     /**
3281      * Reads all content from a file into a string, decoding from bytes to characters
3282      * using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.
3283      * The method ensures that the file is closed when all content have been read
3284      * or an I/O error, or other runtime exception, is thrown.
3285      *
3286      * <p> This method is equivalent to:
3287      * {@code readString(path, StandardCharsets.UTF_8) }
3288      *
3289      * @param   path the path to the file
3290      *
3291      * @return  a String containing the content read from the file
3292      *
3293      * @throws  IOException
3294      *          if an I/O error occurs reading from the file or a malformed or


< prev index next >