zoukankan      html  css  js  c++  java
  • Java文件合并

    文件分割与合并是一个常见需求,比如:上传大文件时,可以先分割成小块,传到服务器后,再进行合并。很多高大上的分布式文件系统(比如:google的GFS、taobao的TFS)里,也是按block为单位,对文件进行分割或合并。

    单线程实现:

     1 package FileDemo;
     2 
     3 import java.io.File;
     4 import java.io.FileInputStream;
     5 import java.io.FileOutputStream;
     6 import java.io.IOException;
     7 import java.io.SequenceInputStream;
     8 import java.util.ArrayList;
     9 import java.util.Collections;
    10 import java.util.Enumeration;
    11 
    12 public class MergeFileDemo {
    13 
    14     //定义缓冲区的大小
    15     private static final int size = 1024 * 1024;
    16 
    17     /**
    18      * @param args
    19      * @throws IOException
    20      */
    21     public static void main(String[] args) throws IOException {
    22 
    23         File srcFile = new File("D:\destFile");
    24         MergeFileTest(srcFile);
    25     }
    26 
    27     private static void MergeFileTest(File srcFile) throws IOException {
    28         ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
    29         for (int x = 1; x <= 4; x++) {
    30             // 将要合并的碎片封装成对象
    31             al.add(new FileInputStream(new File(srcFile, x + ".part")));
    32         }
    33         Enumeration<FileInputStream> en = Collections.enumeration(al);
    34         SequenceInputStream sis = new SequenceInputStream(en);
    35         // 将合成的文件封装成一个文件对象
    36         FileOutputStream fos = new FileOutputStream(new File(srcFile, "1.mp3"));
    37         int len = 0;
    38         byte buf[] = new byte[size];
    39         while ((len = sis.read(buf)) != -1) {
    40             fos.write(buf, 0, len);
    41         }
    42         fos.close();
    43         sis.close();
    44     }
    45 
    46 }
  • 相关阅读:
    浏览器加载AMD标准的输出文件
    Mac安装brew && brew 安装yarn
    插件集
    vue-router复用组件时不刷新数据
    加入sass后运行项目报错:TypeError: this.getResolve is not a function
    安装cnpm后运行报cnpm : 无法加载文件 C:UsersyizonAppDataRoaming pmcnpm.ps1,因为在此系统上禁止运行脚本
    图片canvas跨域问题解决方案之一
    vscode配置
    搭建express服务
    项目初始化
  • 原文地址:https://www.cnblogs.com/ysw-go/p/5308120.html
Copyright © 2011-2022 走看看