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

相关文章

C# 比较两个list 之间元素差异的常用方法

《C#比较两个list之间元素差异的常用方法》:本文主要介绍C#比较两个list之间元素差异,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 使用Except方法2. 使用Except的逆操作3. 使用LINQ的Join,GroupJoin

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

MySQL查询JSON数组字段包含特定字符串的方法

《MySQL查询JSON数组字段包含特定字符串的方法》在MySQL数据库中,当某个字段存储的是JSON数组,需要查询数组中包含特定字符串的记录时传统的LIKE语句无法直接使用,下面小编就为大家介绍两种... 目录问题背景解决方案对比1. 精确匹配方案(推荐)2. 模糊匹配方案参数化查询示例使用场景建议性能优

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

一文详解Git中分支本地和远程删除的方法

《一文详解Git中分支本地和远程删除的方法》在使用Git进行版本控制的过程中,我们会创建多个分支来进行不同功能的开发,这就容易涉及到如何正确地删除本地分支和远程分支,下面我们就来看看相关的实现方法吧... 目录技术背景实现步骤删除本地分支删除远程www.chinasem.cn分支同步删除信息到其他机器示例步骤

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是