Search code examples
javafile-ioinputstream

Does Files.readAllBytes() closes the inputstream after reading the file?


Does this java method close the inputstream after reading the file?

Files.readAllBytes(Paths.get("file"))


Solution

  • Yes, it closes. See it in the javadoc.

    Reads all the bytes from a file. The method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown.

    Note that this method is intended for simple cases where it is convenient to read all bytes into a byte array. It is not intended for reading in large files.

    public static byte[] readAllBytes(Path path) throws IOException {
        try (SeekableByteChannel sbc = Files.newByteChannel(path);
             InputStream in = Channels.newInputStream(sbc)) {
            long size = sbc.size();
            if (size > (long)MAX_BUFFER_SIZE)
                throw new OutOfMemoryError("Required array size too large");
    
            return read(in, (int)size);
        }
    }