java实现文件合并的功能

package com.alanluo.recorder;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class test2 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        List<String> list = new ArrayList<>();
        list.add("D:/1/jasndfjhamsfnaoihjsdfasd.tmp0");
        list.add("D:/1/jasndfjhamsfnaoihjsdfasd.tmp1");

        String targetPath = "D:/1/marge.pcm";


        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            //新建一个目标文件对象
            File target = new File(targetPath);

            //实例化一个文件流输出对象
            out = new FileOutputStream(target);

            //循环读取要合并的文件集合
            for(String path:list) {

                //文件对象
                File file = new File(path);

                if (file.exists()) {

                    System.out.println("filePath:"+file.getAbsolutePath()+" file:"+file.length());

                    byte[] buf = new byte[1024];
                    int len = 0;
                    in = new FileInputStream(file);
                    while ((len = in.read(buf)) != -1) {
                        //写出数据
                        out.write(buf, 0, len);
                    }

                    if (in != null) {
                        in.close();
                    }
                }
            }


        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }


    }

   
}

Leave a Comment

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |