<span>【实用场景】Java合并多个文本文件为单个文件</span>

这段代码通过Java I/O流API实现将多个文件合并到一个文件中,输出为文本文件,提供一个支持语法高亮的网站,http://www.codeinword.com/
适合粘贴代码到word文档,小巧实用,希望可以帮到有需要的你。

/**
 * @author Vincente
 * @date 2020/08/09-21:48
 * @desc
 **/
public class MergeFilesToOne {
    public static void main(String[] args) throws IOException {
        String in = "C:\\Users\\Vincente\\Desktop\\net";
        String out = "D:\\out.txt";
        // 合并
        mergeFileToOne(in, out);
    }

    /**
     * 递归获取文件夹以及子文件夹下的文件
     *
     * @param path
     * @return
     */
    public static List getFiles(String path) {
        List list = new ArrayList();
        File[] files = new File(path).listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                List node = getFiles(files[i].getPath());
                list.addAll(node);
            } else {
                list.add(files[i].getPath());
            }
        }
        return list;
    }


    /**
     * 合并文件
     *
     * @param inPath
     * @param outPath
     * @throws IOException
     */
    public static void mergeFileToOne(String inPath, String outPath) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(outPath));
        System.out.println("--->合并目标文件夹路径:" + inPath);
        System.out.println("--->正在读取文件...");
        List<String> files = getFiles(inPath);
        System.out.println("--->合并文件数量:" + files.size());
        for (int i = 0; i < files.size(); i++) {
            File file = new File(files.get(i));
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                bw.write(line);
                bw.newLine();
            }
            bufferedReader.close();
        }
        System.out.println("--->合并完成!");
        System.out.println("--->合并文件输出路径:" + outPath);
        bw.close();
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务