java 如何将两个txt文件内容写入到一个txt文件中?

时间:2022-05-05 19:56:55
package com.test.mytest.study;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
 
public class Demo001 {
 
    public static void writeFile(String strSrc, String dest) {
        FileWriter writer = null;
        FileReader reader = null;
        BufferedReader br = null;
        BufferedWriter bw = null;
 
        try {
            File file = new File(dest);
            if (!file.exists()) {
                file.createNewFile();
            }
             
            // 这里的true,是以追加的方式写
            writer = new FileWriter(dest, true);
 
            reader = new FileReader(strSrc);
 
            String str = null;
 
            br = new BufferedReader(reader);
 
            bw = new BufferedWriter(writer);
 
            while ((str = br.readLine()) != null) {
                StringBuffer sb = new StringBuffer("");
 
                sb.append(str + "\n");
                bw.write(sb.toString());
            }
 
            br.close();
            reader.close();
 
            bw.close();
            writer.close();
 
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        Demo001.writeFile("D:/1.txt", "D:/3.txt");
        Demo001.writeFile("D:/2.txt", "D:/3.txt");
    }
}