首页 / 博客文章 / Java对大文件分片处理

Java

Java对大文件分片处理

Java实例  云邦 2022-01-12 15:36:08 1270 0条

描述

文件分割与合并是一个常见需求,比如:通过webservice接口发送大文件时,可以先分割成分片小块,然后根据数据块起始位置写成完整文件。

实例

  1. package com.gdie.jxw.gwbl.util;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.RandomAccessFile;
  8. import org.apache.commons.codec.binary.Base64;
  9. public class FileSliceUtil {
  10. // 文件处理
  11. public static void fileHandle() throws IOException {
  12. // 文件拆成分片
  13. String filePath = "D:\\work\\测试文档.DOCX";
  14. // 文件块大小,单位byte
  15. long blockSize = 512000;
  16. // 文件块起始位置
  17. long dataIndex = 0;
  18. Base64 base64 = new Base64();
  19. File tempFile = new File(filePath);
  20. InputStream in = new FileInputStream(tempFile);
  21. // 文件大小
  22. long fileSize = in.available();
  23. System.out.println(">>文件大小:" + fileSize);
  24. // 循环读取文件块内容
  25. while (dataIndex < fileSize) {
  26. // 判断数据起始位置加上读取文件块大小是否超出文件大小,如果超出,重新计算文件块大小
  27. if ((dataIndex + blockSize) > fileSize) {
  28. blockSize = fileSize - dataIndex;
  29. }
  30. byte[] fileBlockContent = new byte[(int) blockSize];
  31. try {
  32. in.read(fileBlockContent, 0, (int) blockSize);
  33. } catch (IOException e2) {
  34. e2.printStackTrace();
  35. }
  36. String fileContent = base64.encodeToString(fileBlockContent);
  37. // 模拟分块写入
  38. sliceInsert(fileContent, dataIndex);
  39. dataIndex = dataIndex + blockSize;
  40. }
  41. // 文件分片写入
  42. System.out.println("分片结束");
  43. }
  44. /**
  45. * 分片插入
  46. * @param content 分片内容
  47. * @param dataIndex 插入位置开始
  48. */
  49. public static void sliceInsert(String content, long dataIndex) {
  50. try {
  51. System.out.println("开始写入了");
  52. byte[] contentInBytes = Base64.decodeBase64(content);
  53. File tmp = File.createTempFile("tmp", null);
  54. String fileName = "D://work//分片组成的文档.DOCX";
  55. tmp.deleteOnExit();
  56. try (RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
  57. FileOutputStream tmpOut = new FileOutputStream(tmp);
  58. FileInputStream tmpIn = new FileInputStream(tmp)) {
  59. raf.seek(dataIndex);
  60. byte[] buf = new byte[64];
  61. int hasRead = 0;
  62. while ((hasRead = raf.read(buf)) > 0) {
  63. tmpOut.write(buf, 0, hasRead);
  64. }
  65. raf.seek(dataIndex);
  66. raf.write(contentInBytes);
  67. while ((hasRead = tmpIn.read(buf)) > 0) {
  68. raf.write(buf, 0, hasRead);
  69. }
  70. }
  71. } catch (Exception e) {
  72. // TODO: handle exception
  73. e.printStackTrace();
  74. }
  75. }
  76. public static void main(String[] args) throws IOException {
  77. fileHandle();
  78. }
  79. }

文章评论

置顶