java - FileChannel.close() 是否关闭底层流?

标签 java nio

喜欢标题;关闭 FileChannel 是否会关闭底层文件流?


来自 AbstractInterruptibleChannel.close()您可以阅读的 API 文档:

Closes this channel.

If the channel has already been closed then this method returns immediately. Otherwise it marks the channel as closed and then invokes the implCloseChannel method in order to complete the close operation.

调用 AbstractInterruptibleChannel.implCloseChannel :

Closes this channel.

This method is invoked by the close method in order to perform the actual work of closing the channel. This method is only invoked if the channel has not yet been closed, and it is never invoked more than once.

An implementation of this method must arrange for any other thread that is blocked in an I/O operation upon this channel to return immediately, either by throwing an exception or by returning normally.

这并没有说明有关流的任何内容。所以事实上,当我这样做时:

public static void copyFile(File from, File to) 
        throws IOException, FileNotFoundException {

    FileChannel sc = null;
    FileChannel dc = null;

    try {
        to.createNewFile();

        sc = new FileInputStream(from).getChannel(); 
        dc = new FileOutputStream(to).getChannel();

        long pos = 0;
        long total = sc.size();
        while (pos < total)
            pos += dc.transferFrom(sc, pos, total - pos);

    } finally {
        if (sc != null) 
            sc.close();
        if (dc != null) 
            dc.close();
    }
}

...我让流保持打开状态?

最佳答案

答案是"is",但 Javadoc 中没有任何内容实际上是这样说的。原因是FileChannel本身是一个抽象类,其具体实现提供了implCloseChannel()方法,关闭了底层FD。然而,由于该架构和 implCloseChannel() 受到保护的事实,这没有得到记录。

关于java - FileChannel.close() 是否关闭底层流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12970407/

相关文章:

java - Gson流关闭

java - 如何测试非阻塞 channel 的 SocketChannel.read() 是否已完成?

Java Files.copy 抛出带有符号链接(symbolic link)的 FileNotFoundException

java - 轻量级低延迟的 Java 网络库?

nio - 使用Java 7新IO获取文件/目录大小

java - Java 非阻塞 io 可以用于所描述的应用程序吗?

java - 在 JPA 中使用数组进行 native 查询

java - 折叠工具栏布局将在 Activity 开始时自动进入折叠状态

java - 应用视频效果

java - 模型 View 同步(或避免同步)