[英]New Line while writing into file
I followed this link and I came up with below code 我点击了此链接,然后想到了以下代码
try {
File file = new File(
"C:/dataset.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
List<Integer> data = generateData(args);
// one per line
for (final int i : data) {
bw.write(i);
bw.newLine(); // Here it throws NullPointerException
}
bw.close();
} catch (IOException e) {
System.out.print(e);
}
NOTE: Even if I move bw.newLine();
注意:即使我移动
bw.newLine();
before for
loop, it throws NullPointerException
. 在
for
循环之前,它抛出NullPointerException
。
Image 图片
Am I missing anything ? 我有什么想念的吗?
To add a line seperator you could use this. 要添加行分隔符,您可以使用它。
//to add a new line after each value added to File
String newLine = System.getProperty("line.separator");
and then call it like so: 然后这样称呼它:
bw.write(newLine);
EDIT: since you cant use a System.getProperty with a BufferWriter I would suggest the code below: 编辑:由于您不能将System.getProperty与BufferWriter一起使用,因此建议以下代码:
private FileOutputStream fOut;
private OutputStreamWriter writer;
fOut = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
writer = new OutputStreamWriter(fOut);
writer.append(.... whatever you wish to append ...);
writer.append(separator);
writer.flush();
fOut.close();
Hope that helps! 希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.