FileChannel主要方法的使用

2024-01-13 15:18

本文主要是介绍FileChannel主要方法的使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

FileChannel介绍

FileChannel类是Channel接口的主要实现类,Channel是NIO的重要组件之一。
FileChannel类的主要作用是读取、写入、映射、操作文件。

write

public abstract int write(ByteBuffer src) throws IOException;

FileChannel内部维护了一个当前文件的position,可以查询、修改position。

/*** int write(ByteBuffer src)将src的remaining的字节写入FileChannel的position。* @throws Exception*/
@Test
public void testWrite() throws Exception {FileOutputStream fos = new FileOutputStream("d:/1.txt");FileChannel fileChannel = fos.getChannel();ByteBuffer b = ByteBuffer.wrap(new byte[]{1,2,3,4,5});int result = fileChannel.write(b);System.out.println("写入了" + result+ "个字节");  // 1,2,3,4,5System.out.println("fileChannel.position()=" + fileChannel.position());fileChannel.position(2);//设置FileChannel的position位置是2b.rewind();result = fileChannel.write(b); //1,2,1,2,3,4,5System.out.println("写入了" + result+ "个字节");b.position(4);result = fileChannel.write(b);System.out.println("写入了" + result+ "个字节"); //1,2,1,2,3,4,5,5fos.close();
}
/*** int write(ByteBuffer src)是同步的,同一时间只能有一个线程写入* @throws Exception*/
@Test
public void testWrite2() throws Exception {FileOutputStream fos = new FileOutputStream("d:/1.txt");FileChannel fileChannel = fos.getChannel();ExecutorService exec = Executors.newFixedThreadPool(100);for (int i = 0; i < 200; i++) {exec.execute(()->{int i2 = new Random().nextInt(2);ByteBuffer byteBuffer;if(i2 % 2 == 0){byteBuffer = ByteBuffer.wrap((Thread.currentThread().getName() + "写入abcde\n").getBytes());}else{byteBuffer = ByteBuffer.wrap((Thread.currentThread().getName() + "写入12345\n").getBytes());}try {Thread.sleep(1);fileChannel.write(byteBuffer);} catch (Exception e) {e.printStackTrace();}});}exec.shutdown();while(!exec.isTerminated()){Thread.sleep(1000);}
}

在这里插入图片描述
写入的文件没有发生数字和字母混合在同一行的情况。

其他write方法

write(ByteBuffer[] srcs) 将ByteBuffer数组srcs里的内容(都是从position到limit处的内容)批量写到当前FileChannel的position开始处。
write(ByteBuffer src, long position)向FileChannel通道的指定position写入src的remaining内容。

read()

和write()一样,同一时间只能有1个线程读取,其他线程阻塞。

public abstract int read(ByteBuffer dst) throws IOException

read方法返回读取了多少个字节,如果是末尾,返回-1。如果dst的remaining用完了,返回0.
read方法会将FileChannel当前position读入1个到dst的remaining字节空间。

/*** 假设1.txt里写入了5个字节:* ByteBuffer b = ByteBuffer.wrap(new byte[]{1,2,3,4,5});* fileChannel.write(b);* @throws Exception*/
@Test
public void testRead() throws Exception {FileInputStream fis = new FileInputStream("d:/1.txt");FileChannel fileChannel = fis.getChannel();ByteBuffer byteBuffer = ByteBuffer.allocate(5);int resultBytesCount = fileChannel.read(byteBuffer);System.out.println("读取了" + resultBytesCount+"个字节");   //读取了5个字节System.out.println("fileChannel.position()=" + fileChannel.position()); //fileChannel.position()=5resultBytesCount = fileChannel.read(byteBuffer);System.out.println("读取了" + resultBytesCount+"个字节");  //读取了0个字节System.out.println("fileChannel.position()=" + fileChannel.position()); //fileChannel.position()=5byteBuffer.clear();resultBytesCount = fileChannel.read(byteBuffer);System.out.println("读取了" + resultBytesCount+"个字节");  //读取了-1个字节,因为FileChannel已经到头了System.out.println("fileChannel.position()=" + fileChannel.position()); //fileChannel.position()=5fileChannel.position(1);byteBuffer.position(1);resultBytesCount = fileChannel.read(byteBuffer); //从byteBuffer的position=1处开始读,读入到fileChannel的position=1处System.out.println("读取了" + resultBytesCount+"个字节");  //读取了4个字节System.out.println("fileChannel.position()=" + fileChannel.position()); //fileChannel.position()=5fileChannel.close();;fis.close();
}

在这里插入图片描述

其他read方法

read(ByteBuffer[] dsts) 将FileChannel的当前position开始字节读取到,ByteBuffer数组dsts的每一个ByteBuffer的position到limit。
int read(ByteBuffer dst, long position) 将FileChannle的指定position开始的内容读入到dst的position处。

size

long size() 返回此FileChannel关联文件的大小

例如使用FileChannel完成文件的读取

/*** 假定文件已经存在,使用ByteBuffer和FileChannel将文件中的数据读入到程序,并显示在控制台屏幕。*/
@Test
public void testSize() throws Exception {File file = new File("d:\\1.txt");FileInputStream fileInputStream = new FileInputStream(file);FileChannel fileChannel = fileInputStream.getChannel();ByteBuffer byteBuffer = ByteBuffer.allocate((int) fileChannel.size());fileChannel.read(byteBuffer);//将byteBuffer 的 字节数据 转成StringSystem.out.println(new String(byteBuffer.array()));fileInputStream.close();
}/*** 使用 FileChannel完成文件的拷贝。拷贝一个文件 1.txt*/
public void testReadAndWrite() throws Exception{FileInputStream fileInputStream = new FileInputStream("1.txt");FileChannel fileChannel1 = fileInputStream.getChannel();FileOutputStream fileOutputStream = new FileOutputStream("2.txt");FileChannel fileChannel2 = fileOutputStream.getChannel();ByteBuffer byteBuffer = ByteBuffer.allocate(512);while (true) {byteBuffer.clear(); //清空bufferint read = fileChannel1.read(byteBuffer);if(read == -1) { //表示读完break;}byteBuffer.flip();fileChannel2.write(byteBuffer);}fileInputStream.close();fileOutputStream.close();
}

transFrom & transTo

long transferFrom(ReadableByteChannel src,long position, long count) 将数据从src通道中的position开始传输最大count个字节到当前FileChannel通道。
long transferTo(long position, long count,WritableByteChannel target) 将FileChannel中position处开始的字节传输最大count个字节到另外一个通道。如果position>FileChannel大小,不传输任何字节。

用transFrom完成文件的拷贝

/*** 使用 FileChannel(通道) 和 方法  transferFrom ,完成文件的拷贝*/
public void testTransferFrom() throws Exception{FileInputStream fileInputStream = new FileInputStream("d:\\1.txt");FileOutputStream fileOutputStream = new FileOutputStream("d:\\1.txt");FileChannel sourceCh = fileInputStream.getChannel();FileChannel destCh = fileOutputStream.getChannel();//使用transferForm完成拷贝destCh.transferFrom(sourceCh,0,sourceCh.size());//关闭相关通道和流sourceCh.close();destCh.close();fileInputStream.close();fileOutputStream.close();
}

这篇关于FileChannel主要方法的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/601898

相关文章

使用Java将DOCX文档解析为Markdown文档的代码实现

《使用Java将DOCX文档解析为Markdown文档的代码实现》在现代文档处理中,Markdown(MD)因其简洁的语法和良好的可读性,逐渐成为开发者、技术写作者和内容创作者的首选格式,然而,许多文... 目录引言1. 工具和库介绍2. 安装依赖库3. 使用Apache POI解析DOCX文档4. 将解析

Qt中QUndoView控件的具体使用

《Qt中QUndoView控件的具体使用》QUndoView是Qt框架中用于可视化显示QUndoStack内容的控件,本文主要介绍了Qt中QUndoView控件的具体使用,具有一定的参考价值,感兴趣的... 目录引言一、QUndoView 的用途二、工作原理三、 如何与 QUnDOStack 配合使用四、自

C++使用printf语句实现进制转换的示例代码

《C++使用printf语句实现进制转换的示例代码》在C语言中,printf函数可以直接实现部分进制转换功能,通过格式说明符(formatspecifier)快速输出不同进制的数值,下面给大家分享C+... 目录一、printf 原生支持的进制转换1. 十进制、八进制、十六进制转换2. 显示进制前缀3. 指

Python列表去重的4种核心方法与实战指南详解

《Python列表去重的4种核心方法与实战指南详解》在Python开发中,处理列表数据时经常需要去除重复元素,本文将详细介绍4种最实用的列表去重方法,有需要的小伙伴可以根据自己的需要进行选择... 目录方法1:集合(set)去重法(最快速)方法2:顺序遍历法(保持顺序)方法3:副本删除法(原地修改)方法4:

Python中判断对象是否为空的方法

《Python中判断对象是否为空的方法》在Python开发中,判断对象是否为“空”是高频操作,但看似简单的需求却暗藏玄机,从None到空容器,从零值到自定义对象的“假值”状态,不同场景下的“空”需要精... 目录一、python中的“空”值体系二、精准判定方法对比三、常见误区解析四、进阶处理技巧五、性能优化

使用Python构建一个Hexo博客发布工具

《使用Python构建一个Hexo博客发布工具》虽然Hexo的命令行工具非常强大,但对于日常的博客撰写和发布过程,我总觉得缺少一个直观的图形界面来简化操作,下面我们就来看看如何使用Python构建一个... 目录引言Hexo博客系统简介设计需求技术选择代码实现主框架界面设计核心功能实现1. 发布文章2. 加

C++中初始化二维数组的几种常见方法

《C++中初始化二维数组的几种常见方法》本文详细介绍了在C++中初始化二维数组的不同方式,包括静态初始化、循环、全部为零、部分初始化、std::array和std::vector,以及std::vec... 目录1. 静态初始化2. 使用循环初始化3. 全部初始化为零4. 部分初始化5. 使用 std::a

如何将Python彻底卸载的三种方法

《如何将Python彻底卸载的三种方法》通常我们在一些软件的使用上有碰壁,第一反应就是卸载重装,所以有小伙伴就问我Python怎么卸载才能彻底卸载干净,今天这篇文章,小编就来教大家如何彻底卸载Pyth... 目录软件卸载①方法:②方法:③方法:清理相关文件夹软件卸载①方法:首先,在安装python时,下

电脑死机无反应怎么强制重启? 一文读懂方法及注意事项

《电脑死机无反应怎么强制重启?一文读懂方法及注意事项》在日常使用电脑的过程中,我们难免会遇到电脑无法正常启动的情况,本文将详细介绍几种常见的电脑强制开机方法,并探讨在强制开机后应注意的事项,以及如何... 在日常生活和工作中,我们经常会遇到电脑突然无反应的情况,这时候强制重启就成了解决问题的“救命稻草”。那

kali linux 无法登录root的问题及解决方法

《kalilinux无法登录root的问题及解决方法》:本文主要介绍kalilinux无法登录root的问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,... 目录kali linux 无法登录root1、问题描述1.1、本地登录root1.2、ssh远程登录root2、