快捷搜索: 王者荣耀 脱发

用Java实现某个目录下指定文件类型的内容合并

  有一个任务,需要把一个项目中的所有Java文件代码合并到一个文件里,几百个文件要是一个一个复制岂不是累死,所以直接写了一小段代码自动合并。   思路是先对指定目录进行搜索,获取所有指定文件的File对象,然后进行IO操作就可以了。


代码如下:

package merge;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;

public class Merge {
          
   
    static File targetPath = new File("指定目录路径");
    static ArrayList<File> pathList = new ArrayList<File>();

    public static void main(String[] args) throws Exception {
        if (targetPath.exists()) { // 判断是否为有效目录
            dfsPath(targetPath);
            fileIO();
        } else {
            throw new Exception("路径错误");
        }
    }

    /**
     * 深度优先搜索指定文件
     * 
     * @param file
     */
    public static void dfsPath(File file) {
        for (File indexFile : file.listFiles()) {
            if (indexFile.isDirectory()) {
                dfsPath(indexFile);
            }
            if (indexFile.isFile()) {
                if (indexFile.getName().contains(".java")) { // 判断文件类型
                    pathList.add(indexFile);
                }
            }
        }
    }

    /**
     * 文件IO操作
     * 
     * @throws Exception
     */
    public static void fileIO() throws Exception {
        File outFile = new File("out.txt");
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outFile));
        for (File file : pathList) {
            InputStream in = new FileInputStream(file);
            byte[] temp = new byte[1024];
            int readLength = 0;
            while ((readLength = in.read(temp)) != -1) {
                outputStream.write(temp, 0, readLength);
            }
            in.close();
            outputStream.write("
".getBytes()); // 添加一个换行
            outputStream.flush();
        }
        outputStream.close();
    }
}
经验分享 程序员 微信小程序 职场和发展