java 文件按行读写

时间:2022-09-25 09:18:21
 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:/hw31a.txt", "D:/hw31c.txt");
Demo001.writeFile("D:/hw31b.txt", "D:/hw31c.txt");
}
}