2014-01-06 37 views
0

我想追加到一個文本文件,但由於某種原因,它不斷改寫它,這是我的代碼:安卓:附加到文件,而不是ovewriting

File logFile = new File(Environment.getExternalStorageDirectory().toString(), "notifications.txt"); 
       try { 
       if(!logFile.exists()) { 
        logFile.createNewFile(); 
       } 

       StringBuilder text = new StringBuilder(); // build the string 
       String line; 
       BufferedReader br = new BufferedReader(new FileReader(logFile)); //Buffered reader used to read the file 
       while ((line = br.readLine()) != null) { // if not empty continue 
        text.append(line); 
        text.append('\n'); 
       } 
       BufferedWriter output = new BufferedWriter(new FileWriter(logFile)); 
       output.write(text + "\n"); 
       output.close(); 
       alertDialog.show(); 
       } catch (IOException ex) { 
        System.out.println(ex); 
       } 

預先感謝您

回答

4

使用

new FileWriter(logFile, true) 

其中第二個參數告訴它追加,而不是覆蓋。

找到this question.在右邊的相關問題。

文檔可以發現here

1

您需要使用的FileWriter其他構造函數指定數據是否被覆蓋或追加。使用FileWriter(logFile, true)而不是你現在擁有的:)

相關問題