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();
   }
}

运行上面代码输出

链接:https://www.learnfk.comhttps://www.learnfk.com/java-nio/java-nio-file-channel.html

来源:LearnFk无涯教程网

Hello World! Welcome to LearnFk

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

技术教程推荐

邱岳的产品手记 -〔邱岳〕

从0开始学微服务 -〔胡忠想〕

小马哥讲Spring AOP编程思想 -〔小马哥〕

手把手教你玩音乐 -〔邓柯〕

程序员的个人财富课 -〔王喆〕

去无方向的信 -〔小麥〕

运维监控系统实战笔记 -〔秦晓辉〕

LangChain 实战课 -〔黄佳〕

云原生基础架构实战课 -〔潘野〕

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