Home > Enterprise >  Do I need to close a file (opened using Paths) manually in Java?
Do I need to close a file (opened using Paths) manually in Java?

Time:01-21

New to Java.
My code goes like this:

        try {
            String message = new String ( Files.readAllBytes(Paths.get("src/test.txt")));
            // ... other operations
        } catch (IOException e) {
            e.printStackTrace();
        }

Do I need to do something to prevent memory leak? I suppose that any file stream should be closed, but I can't find a way to do it since I'm using Paths.
Thanks!

CodePudding user response:

Let's take a look at the source code:

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

This method ensures that the file is closed when all bytes have been read or an I/O error or other runtime exception is thrown. So,this method close the input stream after reading the file.

  •  Tags:  
  • Related