关于使用 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)每次将一个素数写入到文件中,所以效率不是很高.最好是使用更大的缓冲区并加载多个素数. 本例重复使用三个不同的视图缓冲区加载字节缓冲区并尽可能加入更多 ...
随机推荐
- Stream的去重排序
1.List<Integer>排序 List<Integer> list = new ArrayList<>();list.add(50);list.add(25) ...
- Django项目:CRM(客户关系管理系统)--48--39PerfectCRM实现登录+验证码+过期时间+页面保留账号
# gbacc_urls.py # ————————38PerfectCRM实现全局账号登录注销———————— from django.conf.urls import url from gbacc ...
- windows 和 mac 文件夹共享问题汇总
目标:windows上的文件夹,共享给MAC,mac可以将文件复制到windows上来 windows设置共享文件夹,然后在mac上访问 假设win的ip地址是10.10.27.11,则mac上远程方 ...
- 正确而又严谨得ajax原生创建方式
自己去封装一个xhr对象是一件比较麻烦的事情.其实也不麻烦,注意逻辑和一个ie6兼容方案(可无),和一个304 其他2开头的status都可以就好了 <!DOCTYPE html> < ...
- 20190814-A Second
一秒,或是,第二次? 这考试也太频繁了吧…… 考试过程: 看三道题. T1没思路. 然后去厕所清醒了一下. 在厕所的时候,突然想到可以离散化. 于是就这么搞了. 然后去写T2. T2好像是数学题. 于 ...
- fill memset, for小测试
/*很无聊写着玩玩,后来发现memset效率会比fill高出这么多,可惜一般只用来赋值0,-1......以后可以用fill来偷偷懒了...*/ #include<iostream> #i ...
- 分布式事务 XA 两段式事务 X/open CAP BASE 一次分清
分布式事务: 分布式事务是处理多节点上 的数据保持 类似传统 ACID 事物特性的 一种事物. XA:是一种协议,一种分布式事务的协议,核心思想是2段式提交. 1 准备阶段 2 提交阶段.XA协议是 ...
- Intent 传递Map数据
android开发默认情况下,通过Bundle bundle=new Bundle();传递值是不能直接传递map对象的,解决办法: 第一步:封装自己的map,实现序列化即可 /** *序列化map供 ...
- Prime Ring Problem HDU - 1016 (dfs)
Prime Ring Problem HDU - 1016 A ring is compose of n circles as shown in diagram. Put natural number ...
- 序列化form表单
// 序列化JSON字符串 $.fn.serializeObject = function () { let o = {}; let a = this.serializeArray(); $.each ...