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

Print this page

        

@@ -23,23 +23,24 @@
  * questions.
  */
 
 package java.nio.file;
 
-import java.nio.ByteBuffer;
 import java.nio.file.attribute.*;
 import java.nio.file.spi.FileSystemProvider;
 import java.nio.file.spi.FileTypeDetector;
+import java.nio.channels.Channels;
 import java.nio.channels.FileChannel;
 import java.nio.channels.SeekableByteChannel;
 import java.io.Closeable;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.io.Reader;
 import java.io.Writer;
 import java.io.BufferedReader;
 import java.io.BufferedWriter;
+import java.io.ByteArrayOutputStream;
 import java.io.InputStreamReader;
 import java.io.OutputStreamWriter;
 import java.io.IOException;
 import java.io.UncheckedIOException;
 import java.util.*;

@@ -2992,21 +2993,20 @@
         try (FileChannel fc = FileChannel.open(path)) {
             long size = fc.size();
             if (size > (long)Integer.MAX_VALUE)
                 throw new OutOfMemoryError("Required array size too large");
 
-            byte[] arr = new byte[(int)size];
-            ByteBuffer bb = ByteBuffer.wrap(arr);
-            while (bb.hasRemaining()) {
-                if (fc.read(bb) < 0) {
-                    // truncated
-                    break;
+            try (InputStream fis = Channels.newInputStream(fc);
+                 ByteArrayOutputStream bos = new ByteArrayOutputStream((int)size) {
+                     @Override
+                     public byte[] toByteArray() {
+                         return (buf.length == count) ? buf : Arrays.copyOf(buf, count);
                 }
+                 }) {
+                copy(fis, bos);
+                return bos.toByteArray();
             }
-
-            int nread = bb.position();
-            return (nread == size) ? arr : Arrays.copyOf(arr, nread);
         }
     }
 
     /**
      * Read all lines from a file. This method ensures that the file is