java merge contents of multiple files into one file

java merge contents of multiple files into one file

Use the IO operation in the java syntax to write the contents of multiple specified files into one file.
Don't talk nonsense, go directly to the code demonstration

public static void main(String[] args) {
    
    
    //long ss=System.currentTimeMillis();
     //第一个参数为源文件,第二个参数为将源文件放到哪个位置
     mergeFile(new File("E:/javapro/javase"),new File("f:/javase.txt"));
    //System.out.println(System.currentTimeMillis()-ss);
}
//rw方法为文件的写入,可以按照下面的文本格式进行写入
public static void rw(File src, File dst) {
    
    
    try (var is = new FileInputStream(src); var os = new FileOutputStream(dst,true)) {
    
    
        String txt = """
                --------------------------------------------------------\r\n
                文件名:%s\r\n
                行数:%d\r\n
                时间:%tF %<tT\r\n
                路径:%s\r\n
                --------------------------------------------------------\r\n
                %s                    
                """;
         //读取目标文件的所有字节并转换为字符串
        String st = new String(is.readAllBytes());
        StringBuilder sbu = new StringBuilder();
        //提供原子操作的 Integer 类,通过线程安全的方式操作加减
        AtomicInteger num = new AtomicInteger();
        st.lines().forEach(row -> {
    
    
            sbu.append(String.format("%d. %s\r\n", num.getAndIncrement(), row));
        });
        sbu.append("\r\n\r\n");
        //进行格式化
        String ok = String.format(txt, src.getName(), st.lines().count(), src.lastModified(), src.getAbsolutePath(), sbu);
        //写入目标文件
        os.write(ok.getBytes());
    } catch (Exception e) {
    
    
        System.out.println(e);
    }
}
//创建一个方法,判断改文件是不是目录或者文件,运用递归,直到是文件为止。
public static void mergeFile(File src, File dst) {
    
    
    if (src.isDirectory()) {
    
    
        for (File ff : src.listFiles()) {
    
    
            if (ff.isDirectory()) {
    
    
                mergeFile(ff, dst);
            }
            //这里判断是是以".java"结尾的文件,也可以改成其它的文件类型如".html"、".txt"等等
            else if (ff.isFile() && ff.getName().endsWith(".java")) {
    
    
                rw(ff, dst);//如果是文件类型,则调用rw方法
            }
        }
    }//这里同样也要进行判断一下文件的类型,不判断的话,就会将所有类型的文件输入到目标文件中 
    else if (src.isFile() && src.getName().endsWith(".java")) {
    
    
        rw(src, dst);
    }
}

Show results:
insert image description here

Guess you like

Origin blog.csdn.net/qq_59088934/article/details/128561779