简体   繁体   中英

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

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM