如前所述,引入了Java NIO通道的FileChannel实现来访问文件的元数据属性,包括创建,修改,大小等。此文件通道还具有多线程功能,这又使Java NIO比Java IO更高效。
无涯教程不能直接获取文件通道对象,文件通道的对象可以通过以下获得
getChannel() - FileInputStream,FileOutputStream或RandomAccessFile上的任何方法。
open() - 文件通道的方法,默认情况下会打开通道。
File Channel通道的对象类型取决于从对象创建中调用的类的类型,即如果对象是通过调用FileInputStream的getChannel方法创建的,则打开File通道以进行读取,并在尝试写入时抛出NonWritableChannelException。
以下示例显示了如何从Java NIO FileChannel读取和写入数据。
以下示例从C:/Test/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 LearnFK".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 LearnFk
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)