2011-05-13 39 views
0

我想寫一些新的行文本到一個現有的文件。我試過下面的代碼,但失敗了,任何人都可以建議如何追加到文件中的新行。追加到一個新行中的現有文件

private void writeIntoFile1(String str) { 
    try { 
     fc=(FileConnection) Connector.open("file:///SDCard/SpeedScence/MaillLog.txt"); 
     OutputStream os = fc.openOutputStream(fc.fileSize()); 
     os.write(str.getBytes()); 
     os.close(); 
     fc.close(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

,並呼籲

writeIntoFile1("aaaaaaaaa"); 
writeIntoFile1("bbbbbb"); 

它成功地寫我的模擬文件(SD卡),但它的出現在同一行。 如何將「bbbbbb」寫入新行?

回答

1

在寫入字符串後編寫一個newline\n)。

private void writeIntoFile1(String str) { 
    try { 
     fc = (FileConnection) Connector.open("file:///SDCard/SpeedScence/MaillLog.txt"); 
     OutputStream os = fc.openOutputStream(fc.fileSize()); 
     os.write(str.getBytes()); 
     os.write("\n".getBytes()); 
     os.close(); 
     fc.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

N.B. a PrintStream通常更適合打印文本,但我對BlackBerry API不夠熟悉,不知道是否可以使用PrintStream。隨着PrintStream你只是用println()

private void writeIntoFile1(String str) { 
    try { 
     fc = (FileConnection) Connector.open("file:///SDCard/SpeedScence/MaillLog.txt"); 
     PrintStream ps = new PrintStream(fc.openOutputStream(fc.fileSize())); 
     ps.println(str.getBytes()); 
     ps.close(); 
     fc.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+0

馬特球,不過我有同樣的問題 – Jisson 2011-05-13 14:11:14

+0

@Jisson我不熟悉的平臺 - 你可能需要使用'\ r \ N'代替'\ n'表示它正確顯示。 – 2011-05-13 14:14:00

+0

BlackBerry確實支持PrintStream。 http://www.blackberry.com/developers/docs/4.0.2api/java/io/PrintStream.html – Swati 2011-05-13 15:36:50