java 文件按行读写

 1 import java.io.BufferedReader;
 2 import java.io.BufferedWriter;
 3 import java.io.File;
 4 import java.io.FileReader;
 5 import java.io.FileWriter;
 6 import java.io.IOException;
 7 
 8 public class Demo001 {
 9 
10     public static void writeFile(String strSrc, String dest) {
11         FileWriter writer = null;
12         FileReader reader = null;
13         BufferedReader br = null;
14         BufferedWriter bw = null;
15 
16         try {
17             File file = new File(dest);
18             if (!file.exists()) {
19                 file.createNewFile();
20             }
21             
22             // 这里的true,是以追加的方式写
23             writer = new FileWriter(dest, true);
24 
25             reader = new FileReader(strSrc);
26 
27             String str = null;
28 
29             br = new BufferedReader(reader);
30 
31             bw = new BufferedWriter(writer);
32 
33             while ((str = br.readLine()) != null) {
34                 StringBuffer sb = new StringBuffer("");
35 
36                 sb.append(str + "\n");
37                 bw.write(sb.toString());
38             }
39 
40             br.close();
41             reader.close();
42 
43             bw.close();
44             writer.close();
45 
46         } catch (IOException e) {
47             e.printStackTrace();
48         }
49     }
50 
51     public static void main(String[] args) {
52         Demo001.writeFile("D:/hw31a.txt", "D:/hw31c.txt");
53         Demo001.writeFile("D:/hw31b.txt", "D:/hw31c.txt");
54     }
55 }

 

java 文件按行读写,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。