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 }
  • 相关阅读:
    leetcode——91.解码方法
    leetcode——64.最小路径和
    Layui上传图片2.0版
    LINQ中判断日期时间段
    Http基础
    Js中数组,字符串的常用方法
    C#数组,ArrayList,List区别
    08-01 通过线性回归了解算法流程
    08-00 课程习得
    C-02 推荐系统
  • 原文地址:https://www.cnblogs.com/ysw-go/p/5308120.html
Copyright © 2011-2022 走看看