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

相关文章

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

便携式气象仪器的主要特点

TH-BQX9】便携式气象仪器,也称为便携式气象仪或便携式自动气象站,是一款高度集成、低功耗、可快速安装、便于野外监测使用的高精度自动气象观测设备。以下是关于便携式气象仪器的详细介绍:   主要特点   高精度与多功能:便携式气象仪器能够采集多种气象参数,包括但不限于风速、风向、温度、湿度、气压等,部分高级型号还能监测雨量和辐射等。数据采集与存储:配备微电脑气象数据采集仪,具有实时时钟、数据存

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

pdfmake生成pdf的使用

实际项目中有时会有根据填写的表单数据或者其他格式的数据,将数据自动填充到pdf文件中根据固定模板生成pdf文件的需求 文章目录 利用pdfmake生成pdf文件1.下载安装pdfmake第三方包2.封装生成pdf文件的共用配置3.生成pdf文件的文件模板内容4.调用方法生成pdf 利用pdfmake生成pdf文件 1.下载安装pdfmake第三方包 npm i pdfma

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

浅谈主机加固,六种有效的主机加固方法

在数字化时代,数据的价值不言而喻,但随之而来的安全威胁也日益严峻。从勒索病毒到内部泄露,企业的数据安全面临着前所未有的挑战。为了应对这些挑战,一种全新的主机加固解决方案应运而生。 MCK主机加固解决方案,采用先进的安全容器中间件技术,构建起一套内核级的纵深立体防护体系。这一体系突破了传统安全防护的局限,即使在管理员权限被恶意利用的情况下,也能确保服务器的安全稳定运行。 普适主机加固措施: