Discuss / Java / 用Files操作文件不用关闭、释放资源吗?

用Files操作文件不用关闭、释放资源吗?

Topic source

用Files操作文件不用关闭、释放资源吗?

最后不需要类似close()这样关闭释放资源吗

同问

廖雪峰

#3 Created at ... [Delete] [Delete and Lock User]

打开IDE,输入Files.readString(...)

按Ctrl点击readString查看源码,追踪到readAllBytes():

    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);
        }
    }

看到那个try(resources)了吗?这样心里就有谱了。

try()

{}

与python的with open()类似


  • 1

Reply