Channel基本使用——FileChannel类和内存映射的使用

本文详细介绍了Java NIO中的FileChannel,包括如何创建、从FileChannel读取和写入数据,以及利用内存映射文件高效复制大文件的方法。FileChannel不支持非阻塞模式,并且通常通过InputStream、OutputStream或RandomAccessFile获得。通过FileChannel.read()和FileChannel.write()方法进行数据传输,对于大文件复制,内存映射文件提供了更快的解决方案。
摘要由CSDN通过智能技术生成

Channel

基本上,所有的 IO 在NIO 中都从一个Channel 开始。Channel 有点象流。 数据可以从Channel读到Buffer中,也可以从Buffer 写到Channel中。这里有个图示:
在这里插入图片描述
JAVA NIO中的一些主要Channel的实现:

  • FileChannel
  • DatagramChannel
  • SocketChannel
  • ServerSocketChannel

其中后三个主要用于网络编程,第一个是对文件的操作。

FileChannel类

Java NIO中的FileChannel是一个连接到文件的通道。可以通过文件通道读写文件。
FileChannel无法设置为非阻塞模式,它总是运行在阻塞模式下。

一、创建FileChannel

主要有两种创建方式:
第一种:使用一个InputStream、OutputStream或RandomAccessFile来获取一个FileChannel实例。
第二种:JDK1.7之后才能使用, FileChannel.open()方法。

//InputStream、OutputStream或RandomAccessFile,创建FileChannel
RandomAccessFile raf = new RandomAccessFile("D:\\Java\\gp.txt", "r");
FileChannel channel = raf.getChannel();

FileInputStream fis = new FileInputStream("D:\\Java\\gp.txt");
FileChannel channel1 = fis.getChannel();

FileChannel channel2 = new FileOutputStream("D:\\Java\\gp.txt").getChannel();

//FileChannel.open()方法创建Channel
//Paths.get()获取路径,StandardOpenOption.READ表示读的模式
FileChannel readChannel = FileChannel.open(Paths.get("D:\\Java\\gp.jpg"), StandardOpenOption.READ);

//CREATE,如果文件存在就不创建,不存在就创建
FileChannel writeChanne1 = FileChannel.open(Paths.get("D:\\Java\\gp.jpg"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);

//APPEND表示追加写入
FileChannel fileChannel = FileChannel.open(Paths.get("D:\\Java\\gp.txt"), StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.APPEND);

二、从FileChannel读取数据

//读取数据,但是隐含“写”的过程,另外如果读到流的结尾,可能返回0或-1,
int read(ByteBuffer dst);
long read(ByteBuffer[] dsts);
long read
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值