分片读取文件方法:

  1. /**
  2. * 分片读取文件块
  3. *
  4. * @param path 文件路径
  5. * @param position 角标
  6. * @param blockSize 文件块大小
  7. * @return 文件块内容
  8. */
  9. public static byte[] read(String path, long position, int blockSize) throws Exception {
  10. // ----- 校验文件,当文件不存在时,抛出文件不存在异常
  11. checkFilePath(path, false);
  12. // ----- 读取文件
  13. ByteBuffer block = ByteBuffer.allocate(blockSize);
  14. try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get(path), StandardOpenOption.READ)) {
  15. Future<Integer> read = channel.read(block, position);
  16. while (!read.isDone()) {
  17. // ----- 睡1毫秒, 不抢占资源
  18. Thread.sleep(1L);
  19. }
  20. }
  21. return block.array();
  22. }

分片写文件方法:

  1. /**
  2. * 分片写文件
  3. *
  4. * @param path 文件目标位置
  5. * @param block 文件块内容
  6. * @param position 角标
  7. * @throws Exception
  8. */
  9. public static void write(String path, byte[] block, long position) throws Exception {
  10. // ----- 校验文件,当文件不存在时,创建新文件
  11. checkFilePath(path, true);
  12. // ----- 写文件
  13. ByteBuffer buffer = ByteBuffer.wrap(block);
  14. try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get(path), StandardOpenOption.WRITE)) {
  15. Future<Integer> write = channel.write(buffer, position);
  16. while (!write.isDone()) {
  17. // ----- 睡1毫秒, 不抢占资源
  18. Thread.sleep(1L);
  19. }
  20. }
  21. }

检查文件是否存在方法:

  1. /**
  2. * 校验文件
  3. *
  4. * @param path 文件路径
  5. * @param flag 当文件不存在时是否创建文件 [true: 创建文件;false: 抛出文件不存在异常]
  6. * @return
  7. * @throws Exception
  8. */
  9. public static File checkFilePath(String path, boolean flag) throws Exception {
  10. if (StringUtils.isBlank(path)) {
  11. throw new RuntimeException("The file path cannot be empty.");
  12. }
  13. File file = new File(path);
  14. if (!file.exists()) {
  15. if (flag) {
  16. // ----- 当文件不存在时,创建新文件
  17. if (!file.createNewFile()) {
  18. throw new RuntimeException("Failed to create file.");
  19. }
  20. } else {
  21. // ----- 抛出文件不存在异常
  22. throw new RuntimeException("File does not exist.");
  23. }
  24. }
  25. return file;
  26. }

测试:

  1. /*** 分片读写文件的每片默认大小: 10M */
  2. private static final Integer DEFAULT_BLOCK_SIZE = 1024 * 1024 * 10;
  3.  
  4. public static void main(String[] args) throws Exception {
  5. String path = "F:\\compression\\Spring源码深度解析.pdf";
  6. String toPath = "F:\\compression\\" + System.currentTimeMillis() + ".pdf";
  7. File file = FileUtil.checkFilePath(path, false);
  8. long position = 0, length = file.length();
  9. while (length > DEFAULT_BLOCK_SIZE) {
  10. // ----- 如果文件大小大于默认分块大小,循环读写文件,每次循环读取一块,直到剩余文件大小小于默认分块大小
  11. byte[] block = FileUtil.read(path, position, DEFAULT_BLOCK_SIZE);
  12. FileUtil.write(toPath, block, position);
  13. position += DEFAULT_BLOCK_SIZE;
  14. length -= DEFAULT_BLOCK_SIZE;
  15. }
  16. if (length > 0) {
  17. // ----- 如果文件大小小于默认分块大小且大于零,正常读写文件
  18. byte[] block = FileUtil.read(path, position, (int) length);
  19. FileUtil.write(toPath, block, position);
  20. }
  21. }

关于使用 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. Stream的去重排序

    1.List<Integer>排序 List<Integer> list = new ArrayList<>();list.add(50);list.add(25) ...

  2. Django项目:CRM(客户关系管理系统)--48--39PerfectCRM实现登录+验证码+过期时间+页面保留账号

    # gbacc_urls.py # ————————38PerfectCRM实现全局账号登录注销———————— from django.conf.urls import url from gbacc ...

  3. windows 和 mac 文件夹共享问题汇总

    目标:windows上的文件夹,共享给MAC,mac可以将文件复制到windows上来 windows设置共享文件夹,然后在mac上访问 假设win的ip地址是10.10.27.11,则mac上远程方 ...

  4. 正确而又严谨得ajax原生创建方式

    自己去封装一个xhr对象是一件比较麻烦的事情.其实也不麻烦,注意逻辑和一个ie6兼容方案(可无),和一个304 其他2开头的status都可以就好了 <!DOCTYPE html> < ...

  5. 20190814-A Second

    一秒,或是,第二次? 这考试也太频繁了吧…… 考试过程: 看三道题. T1没思路. 然后去厕所清醒了一下. 在厕所的时候,突然想到可以离散化. 于是就这么搞了. 然后去写T2. T2好像是数学题. 于 ...

  6. fill memset, for小测试

    /*很无聊写着玩玩,后来发现memset效率会比fill高出这么多,可惜一般只用来赋值0,-1......以后可以用fill来偷偷懒了...*/ #include<iostream> #i ...

  7. 分布式事务 XA 两段式事务 X/open CAP BASE 一次分清

    分布式事务: 分布式事务是处理多节点上 的数据保持 类似传统 ACID 事物特性的 一种事物. XA:是一种协议,一种分布式事务的协议,核心思想是2段式提交. 1 准备阶段  2 提交阶段.XA协议是 ...

  8. Intent 传递Map数据

    android开发默认情况下,通过Bundle bundle=new Bundle();传递值是不能直接传递map对象的,解决办法: 第一步:封装自己的map,实现序列化即可 /** *序列化map供 ...

  9. 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 ...

  10. 序列化form表单

    // 序列化JSON字符串 $.fn.serializeObject = function () { let o = {}; let a = this.serializeArray(); $.each ...