我想在新行中将一些文本写入现有文件。我尝试了以下代码但失败了,任何人都可以建议如何在新行中追加文件。
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");
它成功写入我模拟的文件(SDCard),但它出现在同一行。 如何将“bbbbbb”写入新行?
答案 0 :(得分: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();
}
}
NB 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();
}
}