2011-05-13 65 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