分片读取文件方法:

     /**
* 分片读取文件块
*
* @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 分片读\写文件的更多相关文章

  1. java读/写文件

    读取文件参考:https://blog.csdn.net/weixin_42129373/article/details/82154471 写入文件参考:https://blog.csdn.net/B ...

  2. Java基础之写文件——将素数写入文件中(PrimesToFile)

    控制台程序,计算素数.创建文件路径.写文件. import static java.lang.Math.ceil; import static java.lang.Math.sqrt; import ...

  3. java中多种写文件方式的效率对比实验

    一.实验背景 最近在考虑一个问题:“如果快速地向文件中写入数据”,java提供了多种文件写入的方式,效率上各有异同,基本上可以分为如下三大类:字节流输出.字符流输出.内存文件映射输出.前两种又可以分为 ...

  4. C++ 二进制文件 读 写文件

    1 #include <iostream> 2 #include <string> 3 #include<fstream> 4 using namespace st ...

  5. read(),write() 读/写文件

    read read()是一个系统调用函数.用来从一个文件中,读取指定长度的数据到 buf 中. 使用read()时需要包含的头文件: <unistd.h> 函数原型: ssize_t re ...

  6. Java基础之写文件——从多个缓冲区写(GatheringWrite)

    控制台程序,使用单个写操作将数据从多个缓冲区按顺序传输到文件,这称为集中写(GatheringWrite)操作.这个功能的优势是能够避免在将信息写入到文件中之前将信息复制到单个缓冲区中.从每个缓冲区写 ...

  7. java中IO写文件工具类

    以下是一些依据经常使用java类进行组装的对文件进行操作的类,平时,我更喜欢使用Jodd.io中提供的一些对文件的操作类,里面的方法写的简单易懂. 当中jodd中提供的JavaUtil类中提供的方法足 ...

  8. c# 读/写文件(各种格式)

    最简单的: --------写 //content是要写入文本的字符串 //(@txtPath + @"\" + rid + ".txt");要被写入的TXT ...

  9. Java基础之写文件——缓冲区中的多条记录(PrimesToFile3)

    控制台程序,上一条博文(PrimesToFile2)每次将一个素数写入到文件中,所以效率不是很高.最好是使用更大的缓冲区并加载多个素数. 本例重复使用三个不同的视图缓冲区加载字节缓冲区并尽可能加入更多 ...

随机推荐

  1. 【python之路40】Python 作用域

    python的作用域与javaScript是一样的,参考:http://www.cnblogs.com/sunshuhai/p/9112578.html 一.python是以函数作为作用域的 if 1 ...

  2. 完美解决IE8不支持margin auto问题

    不用js,超级简单,完美支持. body下的整个container .container { overflow: hidden; margin: 0px auto; text-align: cente ...

  3. 纪念——代码首次达到近50K(更新:78.8K 2019行)

    #include<bits/stdc++.h> #define re register #define F(A) for(re int (A)=1;(A)<=8;++(A)) usi ...

  4. 使用JSP渲染Web视图

    Pom文件引入以下依赖 注意,创建SpringBoot整合JSP,一定要为war类型,否则会找不到页面 不要把jsp页面存放在Resources目录下,resources目录是给springboot打 ...

  5. 2019.9.17 csp-s模拟测试45 反思总结

    来了来了,垃圾二连.[指两次发博客] 看了一下题就匆匆回去上课,在课上一边听课一边水oi,大概用1h40min的时间想完三道题.最后回到机房只剩下40min的时间敲代码,于是T1骗了70分就走了… 这 ...

  6. poj 2001 Shortest Prefixes(字典树trie 动态分配内存)

    Shortest Prefixes Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 15610   Accepted: 673 ...

  7. 写论文,没数据?R语言抓取网页大数据

    写论文,没数据?R语言抓取网页大数据 纵观国内外,大数据的市场发展迅猛,政府的扶持也达到了空前的力度,甚至将大数据纳入发展战略.如此形势为社会各界提供了很多机遇和挑战,而我们作为卫生(医学)统计领域的 ...

  8. FZU 1575 小学生的游戏【模拟二分】

    某天,无聊的小斌叫上几个同学玩游戏,其中有比较笨的小兴,比较傻的小雪,可爱的小霞和自以为是的小楠.他们去找聪明的小明去给他们当裁判.判定谁取得游戏胜利. 而这个游戏是由小斌想个1到10000000的数 ...

  9. 从零开始写一个npm包,一键生成react组件(偷懒==提高效率)

    前言 最近写项目开发新模块的时候,每次写新模块的时候需要创建一个组件的时候(包含组件css,index.js,组件js),就只能会拷贝其他组件修改名称 ,但是写了1-2个后发现效率太低了,而且极容易出 ...

  10. java 操作CLOB类型数据

    clob类型,但对于这个类型处理起来还是比较麻烦的,varchar2长度为4000bytes,如果varchar2能满足楼主的需求,建议使用varchar2,下面提供了在Java 中读取clob类型的 ...