Java NIO - 文件通道
描述
如前所述,Java NIO 通道的 FileChannel 实现用于访问文件的元数据属性,包括创建、修改、大小等。此外,文件通道是多线程的,这再次使 Java NIO 比 Java IO 更高效。
一般来说,我们可以说 FileChannel 是一个连接到文件的通道,通过它您可以从文件中读取数据,也可以将数据写入文件。FileChannel 的另一个重要特性是它不能设置为非阻塞模式,并且始终以阻塞模式运行。
我们不能直接获取文件通道对象,文件通道的对象可以通过 − 获取。
getChannel() −方法适用于 FileInputStream、FileOutputStream 或 RandomAccessFile。
open() − 文件通道的方法,默认情况下打开通道。
文件通道的对象类型取决于对象创建时调用的类的类型,即,如果对象是通过调用 FileInputStream 的 getchannel 方法创建的,则文件通道将打开以供读取,如果尝试写入,将抛出 NonWritableChannelException。
示例
以下示例显示如何从 Java NIO FileChannel 读取和写入数据。
以下示例从 C:/Test/temp.txt 中的文本文件读取并将内容打印到控制台。
temp.txt
Hello World!
FileChannelDemo.java
import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.HashSet; import java.util.Set; public class FileChannelDemo { public static void main(String args[]) throws IOException { //将内容附加到现有文件 writeFileChannel(ByteBuffer.wrap("Welcome to TutorialsPoint".getBytes())); //读取文件 readFileChannel(); } public static void readFileChannel() throws IOException { RandomAccessFile randomAccessFile = new RandomAccessFile("C:/Test/temp.txt", "rw"); FileChannel fileChannel = randomAccessFile.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(512); Charset charset = Charset.forName("US-ASCII"); while (fileChannel.read(byteBuffer) > 0) { byteBuffer.rewind(); System.out.print(charset.decode(byteBuffer)); byteBuffer.flip(); } fileChannel.close(); randomAccessFile.close(); } public static void writeFileChannel(ByteBuffer byteBuffer)throws IOException { Set<StandardOpenOption> options = new HashSet<>(); options.add(StandardOpenOption.CREATE); options.add(StandardOpenOption.APPEND); Path path = Paths.get("C:/Test/temp.txt"); FileChannel fileChannel = FileChannel.open(path, options); fileChannel.write(byteBuffer); fileChannel.close(); } }
输出
Hello World! Welcome to TutorialsPoint