Java NIO - FileChannel(文件通道)

Java NIO - FileChannel(文件通道) 首页 / Nio入门教程 / Java NIO - FileChannel(文件通道)

如前所述,引入了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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

技术与商业案例解读 -〔徐飞〕

技术领导力实战笔记 -〔TGO鲲鹏会〕

Go语言从入门到实战 -〔蔡超〕

现代C++编程实战 -〔吴咏炜〕

互联网人的英语私教课 -〔陈亦峰〕

WebAssembly入门课 -〔于航〕

人人都用得上的写作课 -〔涵柏〕

实用密码学 -〔范学雷〕

遗留系统现代化实战 -〔姚琪琳〕

好记忆不如烂笔头。留下您的足迹吧 :)