3

Java 中的 FileChannel 实现了 ReadableByteChannel 和 WritableByteChannel,这使得它们是双向的。

问题

要创建 FileChannel,我需要 FileInputStream(用于读取)和 FileOutputStream(用于写入)。由于我需要实例化两个流,这是否会破坏使它们成为双向的目的?

跟进问题:

我在很多地方看到过引用说明 java.io 是面向流的,而 java.nio 是面向块的(这里)。那为什么要通过InputStream和OutputStream来实例化呢?是面向块的概念,只是对 Streams 的抽象吗?

4

1 回答 1

5

要创建 FileChannel,我需要 FileInputStream(用于读取)和 FileOutputStream(用于写入)。

你没有。您可以使用FileChannel.open(Path, OpenOption...)

Path path = ...;
FileChannel channel = FileChannel.open(path, options)
channel.read(byteBuffer);
channel.write(byteBuffer);

在这里查看您后续问题的答案。

于 2013-09-09T20:50:56.757 回答