2014-03-19 68 views
0
import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.io.PrintWriter; 

public class test3 { 
     public static void main(String[] args) { 

       //write 
       try { 
         FileWriter fw = new FileWriter("C:\\Users\\Danny\\Desktop\\Credits.txt"); 
         PrintWriter pw = new PrintWriter (fw); 

         pw.println("This is just some test data"); 

         pw.close(); 
       } 
       catch (IOException e){ 
         System.out.println("Error!"); 
       } 

       //read 
       try { 
         FileReader fr = new FileReader("C:\\Users\\Danny\\Desktop\\Credits.txt"); 
         BufferedReader br = new BufferedReader (fr); 

         String str; 

         while ((str = br.readLine()) != null) { 
           System.out.println(str + "\n"); 
         } 
         br.close();    

       } 
       catch (IOException e){ 
         System.out.println("File not found!"); 
       } 

     } 
} 

這可以工作,但每次都使用新輸入寫入文本文件。如何在寫入過程中阻止這種情況,以便所有信息都像存檔一樣存儲在文件中。文件編寫器如何停止從文件中寫入文本

+0

所以你要'append'你的文件嗎? –

+0

檢查FileWriter類的構造函數。 'FileWriter(文件文件,布爾附加)' –

回答

0

打開要寫入文件的下一次追加模式的文件。

FileWriter fw = new FileWriter("C:\\Users\\Danny\\Desktop\\Credits.txt",true); 
0

用途:

Files.newBufferedWriter(Paths.get("yourfile"), StandardCharsets.UTF_8, 
    StandardOpenOption.APPEND);