gpt4 book ai didi

Filechannel TransferTO 的 Java 文档规范

转载 作者:行者123 更新时间:2023-12-01 12:13:35 27 4
gpt4 key购买 nike

根据 Java doc, ClosedByInterruptException 在以下情况下抛出:

  @throws  ClosedByInterruptException
If another thread interrupts the current thread while the
transfer is in progress, thereby closing both channels and
setting the current thread's interrupt status

我想得到一些澄清。例如,有一个文件,当新数据添加到其末尾时,该文件偶尔会扩展。在这种情况下,上面的行是否意味着如果在添加新数据时,FileChanneltransferTO 方法尝试复制内容,则会引发异常。

在这里,另一个线程是 Filechannel 的 TransferTO 方法当前线程将是正在尝试向其写入更多数据的线程。

正确吗?

最佳答案

我认为FileChannel的transferTo()方法中存在ClosedByInterruptException当其他线程调用调用线程的interrupt()方法时抛出该异常。

例如:

    import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

public class Test {

public static void main(final String[] args) throws Exception {
final RandomAccessFile fromFile = new RandomAccessFile("d:/pp.dat", "rw");
final FileChannel fromChannel = fromFile.getChannel();

final RandomAccessFile toFile = new RandomAccessFile("d:/out.dat", "rw");
final FileChannel toChannel = toFile.getChannel();

final long position = 0;
final long count = fromChannel.size();
final Runnable r = new Runnable() {
@Override
public void run() {
try {
fromChannel.transferTo(position, count, toChannel);
} catch (final IOException e) {
e.printStackTrace();
}
}
};
final Thread t = new Thread(r);
t.start();
t.interrupt();
}
}

关于您提出的关于另一个线程同时写入的问题(如果我正确理解您的问题),来自javadoc:

文件 channel 可供多个并发线程安全使用。根据 Channel 接口(interface)的规定,可以随时调用 close 方法。在任何给定时间,只有一项涉及 channel 位置或可以更改其文件大小的操作正在进行;当第一个操作仍在进行时尝试启动第二个此类操作将被阻止,直到第一个操作完成。其他操作,特别是那些采取明确立场的操作,可以同时进行;它们实际上是否这样做取决于底层实现,因此未指定。

保证此类的实例提供的文件 View 与同一程序中的其他实例提供的同一文件的其他 View 一致。然而,由于底层操作系统执行的缓存以及网络文件系统协议(protocol)引起的延迟,此类的实例提供的 View 可能与其他并发运行的程序看到的 View 一致,也可能不一致。无论这些其他程序是用什么语言编写的,也无论它们是在同一台机器上还是在其他机器上运行,都是如此。任何此类不一致的确切性质均取决于系统,因此未指定。

关于Filechannel TransferTO 的 Java 文档规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27134465/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com