关于使用 Java 分片读\写文件
分片读取文件方法:
/**
* 分片读取文件块
*
* @param path 文件路径
* @param position 角标
* @param blockSize 文件块大小
* @return 文件块内容
*/
public static byte[] read(String path, long position, int blockSize) throws Exception {
// ----- 校验文件,当文件不存在时,抛出文件不存在异常
checkFilePath(path, false);
// ----- 读取文件
ByteBuffer block = ByteBuffer.allocate(blockSize);
try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get(path), StandardOpenOption.READ)) {
Future<Integer> read = channel.read(block, position);
while (!read.isDone()) {
// ----- 睡1毫秒, 不抢占资源
Thread.sleep(1L);
}
}
return block.array();
}
分片写文件方法:
/**
* 分片写文件
*
* @param path 文件目标位置
* @param block 文件块内容
* @param position 角标
* @throws Exception
*/
public static void write(String path, byte[] block, long position) throws Exception {
// ----- 校验文件,当文件不存在时,创建新文件
checkFilePath(path, true);
// ----- 写文件
ByteBuffer buffer = ByteBuffer.wrap(block);
try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get(path), StandardOpenOption.WRITE)) {
Future<Integer> write = channel.write(buffer, position);
while (!write.isDone()) {
// ----- 睡1毫秒, 不抢占资源
Thread.sleep(1L);
}
}
}
检查文件是否存在方法:
/**
* 校验文件
*
* @param path 文件路径
* @param flag 当文件不存在时是否创建文件 [true: 创建文件;false: 抛出文件不存在异常]
* @return
* @throws Exception
*/
public static File checkFilePath(String path, boolean flag) throws Exception {
if (StringUtils.isBlank(path)) {
throw new RuntimeException("The file path cannot be empty.");
}
File file = new File(path);
if (!file.exists()) {
if (flag) {
// ----- 当文件不存在时,创建新文件
if (!file.createNewFile()) {
throw new RuntimeException("Failed to create file.");
}
} else {
// ----- 抛出文件不存在异常
throw new RuntimeException("File does not exist.");
}
}
return file;
}
测试:
/*** 分片读写文件的每片默认大小: 10M */
private static final Integer DEFAULT_BLOCK_SIZE = 1024 * 1024 * 10; public static void main(String[] args) throws Exception {
String path = "F:\\compression\\Spring源码深度解析.pdf";
String toPath = "F:\\compression\\" + System.currentTimeMillis() + ".pdf";
File file = FileUtil.checkFilePath(path, false);
long position = 0, length = file.length();
while (length > DEFAULT_BLOCK_SIZE) {
// ----- 如果文件大小大于默认分块大小,循环读写文件,每次循环读取一块,直到剩余文件大小小于默认分块大小
byte[] block = FileUtil.read(path, position, DEFAULT_BLOCK_SIZE);
FileUtil.write(toPath, block, position);
position += DEFAULT_BLOCK_SIZE;
length -= DEFAULT_BLOCK_SIZE;
}
if (length > 0) {
// ----- 如果文件大小小于默认分块大小且大于零,正常读写文件
byte[] block = FileUtil.read(path, position, (int) length);
FileUtil.write(toPath, block, position);
}
}
关于使用 Java 分片读\写文件的更多相关文章
- java读/写文件
读取文件参考:https://blog.csdn.net/weixin_42129373/article/details/82154471 写入文件参考:https://blog.csdn.net/B ...
- Java基础之写文件——将素数写入文件中(PrimesToFile)
控制台程序,计算素数.创建文件路径.写文件. import static java.lang.Math.ceil; import static java.lang.Math.sqrt; import ...
- java中多种写文件方式的效率对比实验
一.实验背景 最近在考虑一个问题:“如果快速地向文件中写入数据”,java提供了多种文件写入的方式,效率上各有异同,基本上可以分为如下三大类:字节流输出.字符流输出.内存文件映射输出.前两种又可以分为 ...
- C++ 二进制文件 读 写文件
1 #include <iostream> 2 #include <string> 3 #include<fstream> 4 using namespace st ...
- read(),write() 读/写文件
read read()是一个系统调用函数.用来从一个文件中,读取指定长度的数据到 buf 中. 使用read()时需要包含的头文件: <unistd.h> 函数原型: ssize_t re ...
- Java基础之写文件——从多个缓冲区写(GatheringWrite)
控制台程序,使用单个写操作将数据从多个缓冲区按顺序传输到文件,这称为集中写(GatheringWrite)操作.这个功能的优势是能够避免在将信息写入到文件中之前将信息复制到单个缓冲区中.从每个缓冲区写 ...
- java中IO写文件工具类
以下是一些依据经常使用java类进行组装的对文件进行操作的类,平时,我更喜欢使用Jodd.io中提供的一些对文件的操作类,里面的方法写的简单易懂. 当中jodd中提供的JavaUtil类中提供的方法足 ...
- c# 读/写文件(各种格式)
最简单的: --------写 //content是要写入文本的字符串 //(@txtPath + @"\" + rid + ".txt");要被写入的TXT ...
- Java基础之写文件——缓冲区中的多条记录(PrimesToFile3)
控制台程序,上一条博文(PrimesToFile2)每次将一个素数写入到文件中,所以效率不是很高.最好是使用更大的缓冲区并加载多个素数. 本例重复使用三个不同的视图缓冲区加载字节缓冲区并尽可能加入更多 ...
随机推荐
- springcloud熔断器代码简单实现
Feign包赖熔断器相关的包,所有不用再单独引用 1.在服务消费方的基础上修改,开启熔断机制, feign.hystrix.enabled=true 2.修改消费者调用的接口 package com. ...
- MAC中已有的虚拟环境在pycharm 中进行调用
首先确定虚拟环境的路径: 打开工作环境配置文件,找到工作目录: 在pycharm中解释器中找到工作目录中对应的虚拟环境进行配置就可以了
- URI、URL 和 URN的区别
关于URI:URL类似于住址,它告诉你一种寻找目标的方式. URL和URN都是URI的子集. URI规范:协议名称://域名.根域名/目录/文件名.后缀#sddf URI :Unifor ...
- invalid use of null value
给mysql的数据表的一个字段插入数据,不成功, 然后在数据表设计中,把不是null勾选上,又提示 invalid use of null value 这种情况比较尴尬 只能删掉这一个字段,然后新建一 ...
- Mac OS 安装 独立的asio库
先安装boost,见前文,然后上官网下载不带boost的asio,版本为:asio-1.12.2 cd到下载的库目录,配置 ./configure --with-boost="boost的安 ...
- neo4j中对节点关系和聚类的思考
由于neo4j在查找过程中具有事务,所以查询的速度非常慢!给出的建议如下: 一,将所有查询放在一个Session中,当所有查询完毕以后在关闭Driver和Session: 二,使用neo4j连接池,使 ...
- 提升mysql服务器性能(复制原理与拓扑优化)
原文:提升mysql服务器性能(复制原理与拓扑优化) 版权声明:皆为本人原创,复制必究 https://blog.csdn.net/m493096871/article/details/9008171 ...
- List的深度序列化Demo
今天项目中出现了这个问题...就是使用一个List去进行其他的操作,生成一个新的List.但是却将原来的List的值也给改了...这应该是引用传递的问题,查了资料发现这是浅拷贝造成的.(ps:使用ad ...
- 基于spring-boot的测试桩设计-添加配置文件(properties)
编写测试时,有些内容可以放到配置文件中. 第一步:新增配置文件 conf.properties 第二步:编写配置文件类 MockConf package mock.mockdemo.conf; imp ...
- pip list报错:DEPRECATION: The default format will switch to columns in the future.
一.现象: pip list 显示出以下错误: DEPRECATION: The default format will switch to columns in the future. Yo ...