2016-08-02 37 views
0

我需要在文件中每行的末尾添加循環文本。Java。如何向每行添加文本

例如,我的文件看起來像:

Adam 
Maria 
Jon 

現在,在循環中,我需要添加下一列,看起來像:

Adam|Kowalski 
Maria|Smith 
Jon|Jons 

第3列:

Adam|Kowalski|1999 
Maria|Smith|2013 
Jon|Jons|1983 

等。如何有效地做到這一點? 一個限制我的計劃是,我不知道所有的新價值的增加,我的意思是我不能寫「|科瓦爾斯基| 1999年」畢其功於一役,需要寫「|科瓦爾斯基」,然後在加上 「| 1999年」

感謝

回答

1

你可以嘗試這樣的事情:

public static void main(String[] args) throws Exception {// for test I throw the Exception to keep code shorter. 
    StringBuilder sb = new StringBuilder(); 
    String path = "the/path/to/file"; 
    BufferedReader bReader = new BufferedReader(new FileReader(path)); 
    String line; 
    while ((line = bReader.readLine()) != null) { 
     line += "|"+"the-text-to-add"+"\n\r"; 
     sb.append(line); 
    } 
    bReader.close(); 

    // now write it back to the file 
    OutputStream out = new FileOutputStream(new File(path)); 
    out.write(sb.toString().getBytes()); 
    out.close(); 
} 
相關問題