2013-04-14 45 views
0

這是我讀取文件和寫入文件的代碼;我想將字符串內容寫入文本文件的末尾。我的目標是對文本文件中的光標移動/控制進行命令。如何在文件後寫入文件int文件已經存在(光標移動到文件末尾)

請幫我謝謝

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.IOException; 


public class Filing { 


public static void main(String[] args) throws IOException 
{ 
    String content = "This is the content to write into file"; 

    BufferedReader br = 
    new BufferedReader(new FileReader("C:/Users/Ashad/Desktop/text.txt")); 
    try { 
     StringBuilder sb = new StringBuilder(); 
     String line = br.readLine(); 

     FileWriter fw = new FileWriter("C:/Users/Ashad/Desktop/text.txt"); 
     BufferedWriter bw = new BufferedWriter(fw); 



     while (line != null) 
     { 
      sb.append(line); 
      sb.append("\n"); 
      line = br.readLine(); 
     } 

     //** bw.write(content) ; **// 

     String everything = sb.toString(); 

     System.out.append(everything); 
    } 
    finally 
    { br.close();} 

我couldnot寫的文字已經存在的文件後,字符串的內容。

回答

1

我想寫字符串內容的文本文件的末尾

然後,只需使用需要一個append標誌overload of the FileWriter constructor

FileWriter fw = new FileWriter("C:/Users/Ashad/Desktop/text.txt", true); 

個人雖然,我寧願使用FileOutputStreamOutputStreamWriter - 這樣你可以指定編碼。

+0

可以請你告訴我,是如何工作的?該行如何在文件的末尾寫入字符串? – Asdakamessoy

+0

我沒有得到filewriter的重載 – Asdakamessoy

+0

@AshadChaudhary:爲了清楚起見編輯 - 構造函數被重載;有一個版本,它有一個'boolean'參數是否要追加。 –

1

以附加模式創建的FileWriter:

FileWriter fw = new FileWriter("C:/Users/Ashad/Desktop/text.txt", true); 
相關問題