filechannel java_【原创】java NIO FileChannel 学习笔记 FileChannel 简介

java NIO 中FileChannel 的实现类是  FileChannelImpl,FileChannel本身是一个抽象类。

先介绍FileChannel

File Channels 是线程安全的。Channel的close方法可以随时执行(正如Channel接口所要求的)。任何企图修改filechannel 对应文件大小 或者修改 filechannel position的操作都必须串行执行,第二个操作会一直阻塞直到前一个运行完。不过这些方法,具体还要看如何实现。(下文分析FileChannelImpl)。

创建FileChannel 实例可以通过执行FileChannel的一些方法,比如open方法,或者通过java.io.FileInputStream、java.io.FileOutputStream、java.io.RandomAccessFile的getchannel() 。(ps:网上说RandomAccessFile默认就获取了文件锁,但是我在官网api和RandomAccessFile.java中并未发现相关说明和代码,有人知道是怎么回事的话望不吝赐教,目前我对网上的观点持怀疑态度。)如果使用getChannel获取的FileChannel的话,FileChannel就与FileInputStream或FileOutputStream等对象,产生了关联(后文在分析为何会这样)。也就是说比如当前新建一个FileInputStream对象,然后获取一个FileChannel,此时position是0,然后FileInputStream读取了100字节,读完之后,FIleInputStream下次肯定会从第101个字节读取,这是显而易见的,但是你刚才获取的Channel的position也会移动100。有代码为证:

FileInputStream inputstream = new FileInputStream(sourceFile);

byte[] buffer = new byte[100];

ByteBuffer bb = ByteBuffer.allocate(1024);

FileChannel channel = inputstream.getChannel();

System.out.println("channel "+channel.position());

int read=inputstream.read(buffer);

System.out.println("channel "+channel.position()+" read "+read);

输出结果:

channel 0

channel 100 read 100

继续。FileChannel打开模式有 读、写 和 读and写。FileInputStream获取的自然是读.OutputStream自然是写,RandomAccessFile就看你的RandomAccessFile是何种模式。

FileChannel的追加模式(append-mode)是由所使用的FileOutputStream决定的。追加模式时先跳到文件末尾再开始写,这个操作的原子性是由操作系统支持(FileChannel.java 中的原文 Whether the advancement of the position and the writing of the data are done in a single atomic operation is system-dependent and therefore unspecified)。

使用Java中的FileChannel类和ByteBuffer类来实现NIO操作,可以提高文件读取效率。以下是一个使用NIO读取文件的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class NIOFileReader { public static void main(String[] args) throws IOException { // 打开文件通道 FileChannel fileChannel = new FileInputStream(new File("file.txt")).getChannel(); // 创建一个缓冲区 ByteBuffer buffer = ByteBuffer.allocate(1024); // 从文件通道读取数据到缓冲区 while (fileChannel.read(buffer) != -1) { // 切换读写模式 buffer.flip(); // 读取缓冲区中的数据 while (buffer.hasRemaining()) { System.out.print((char) buffer.get()); } // 清空缓冲区 buffer.clear(); } // 关闭文件通道 fileChannel.close(); } } ``` 在这个示例中,我们首先打开文件通道,然后创建一个ByteBuffer缓冲区来存储读取到的数据。在循环中,我们使用FileChannel的read()方法将数据读取到缓冲区中,然后使用ByteBuffer的flip()方法切换读写模式,从而可以读取缓冲区中的数据。最后使用ByteBuffer的clear()方法清空缓冲区。 需要注意的是,在使用FileChannel读取数据时,需要先将数据读取到缓冲区中,然后再从缓冲区中读取数据。同时,由于缓冲区的大小是有限的,因此需要在循环中反复读取数据,直到读取到文件的末尾为止。 除了读取数据外,FileChannel还可以用于写入数据、截取文件、移动文件指针等操作。使用Java中的NIO操作可以提高文件读取效率,适用于需要频繁读写文件的场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值