Java逐行寫入字符串到文件


 

下邊是寫東西到一個文件中的Java代碼。運行后每一次,一個新的文件被創建,並且之前一個也將會被新的文件替代。這和給文件追加內容是不同的。

 1、

 1     public static void writeFile1() throws IOException {  
 2         File fout = new File("out.txt");  
 3         FileOutputStream fos = new FileOutputStream(fout);  
 4        
 5         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));  
 6        
 7         for (int i = 0; i < 10; i++) {  
 8             bw.write("something");  
 9             bw.newLine();  
10         }  
11        
12         bw.close();  
13     }  
14     

 這個例子使用的是FileOutputStream,你也可以使用FileWriter 或PrintWriter,如果是針對文本文件的操作是完全綽綽有余的。

 

2、使用FileWriter

1   public static void writeFile2() throws IOException {  
2         FileWriter fw = new FileWriter("out.txt");  
3        
4         for (int i = 0; i < 10; i++) {  
5             fw.write("something");  
6         }  
7        
8         fw.close();  
9     }  

 

3、使用PrintWriter: 

1     public static void writeFile3() throws IOException {  
2         PrintWriter pw = new PrintWriter(new FileWriter("out.txt"));  
3        
4         for (int i = 0; i < 10; i++) {  
5             pw.write("something");  //這里也可以用 pw.print("something"); 效果一樣 6         }  
7        
8         pw.close();  
9     }  

 

4、使用OutputStreamWriter: 

 1    public static void writeFile4() throws IOException {  
 2         File fout = new File("out.txt");  
 3         FileOutputStream fos = new FileOutputStream(fout);  
 4        
 5         OutputStreamWriter osw = new OutputStreamWriter(fos);  
 6        
 7         for (int i = 0; i < 10; i++) {  
 8             osw.write("something");  
 9         }  
10        
11         osw.close();  
12     }  

 

 

摘自Java文檔:

 

FileWriter is a convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

FileWriter針對寫字符文件是一個很方便的類。這個類的構造方法假設默認的字符編碼和默認的字節緩沖區都是可以接受的。如果要指定編碼和字節緩沖區的長度,需要構造OutputStreamWriter。


PrintWriter prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.

PrintWriter打印格式化對象的表示到一個文本輸出流。這個類實現了所有在PrintStream中的打印方法。它不包含用於寫入原始字節,因為一個程序應該使用未編碼的字節流。

主要區別在於,PrintWriter提供了一些額外的方法來格式化,例如println和printf。此外,萬一遇到任何的I/O故障FileWriter會拋出IOException。PrintWriter的方法不拋出IOException異常,而是他們設一個布爾標志值,可以用這個值來檢測是否出錯(checkError())。PrintWriter在數據的每個字節被寫入后自動調用flush 。而FileWriter,調用者必須采取手動調用flush.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM