将文本附加到文件时无法成功添加换行符
Can't successfully add a newline when I append text to a file
我创建了一个应用程序,它在设备上创建一个文件,存储大约 5 个值(双)。我认为我正在成功写入文件,因为我在写入文件后立即在设备上看到一条消息。
如果我尝试在命令中添加一个换行符,那么我永远不会看到 toast 消息,因此写入失败。
这是我的工作代码:
try{
String path = this.getFilesDir().getAbsolutePath();
file = new File(path + "/" + filename);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(filename, Context.MODE_PRIVATE));
for (int i = 0; i < priceArray.length; i++) {
outputStreamWriter.append(String.format("%.2f", priceArray[i]));
testText.append(String.format("%.2f", priceArray[i]));
}
Toast.makeText(this, "Prices saved successfully!", Toast.LENGTH_SHORT).show();
outputStreamWriter.close();
}catch (Exception e) {
e.printStackTrace();
}
在文件中单独一行实现条目的最佳方法是什么?
testText.append(String.format("%.2f", priceArray[i]));在我的代码中可以看到这些值,因为我无法在文件系统上找到该文件。
您应该正确格式化:
outputStreamWriter.append(String.format("%.2f\n", priceArray[i]);
注意 %.2f.
之后的 \n
我创建了一个应用程序,它在设备上创建一个文件,存储大约 5 个值(双)。我认为我正在成功写入文件,因为我在写入文件后立即在设备上看到一条消息。
如果我尝试在命令中添加一个换行符,那么我永远不会看到 toast 消息,因此写入失败。
这是我的工作代码:
try{
String path = this.getFilesDir().getAbsolutePath();
file = new File(path + "/" + filename);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(filename, Context.MODE_PRIVATE));
for (int i = 0; i < priceArray.length; i++) {
outputStreamWriter.append(String.format("%.2f", priceArray[i]));
testText.append(String.format("%.2f", priceArray[i]));
}
Toast.makeText(this, "Prices saved successfully!", Toast.LENGTH_SHORT).show();
outputStreamWriter.close();
}catch (Exception e) {
e.printStackTrace();
}
在文件中单独一行实现条目的最佳方法是什么? testText.append(String.format("%.2f", priceArray[i]));在我的代码中可以看到这些值,因为我无法在文件系统上找到该文件。
您应该正确格式化: outputStreamWriter.append(String.format("%.2f\n", priceArray[i]); 注意 %.2f.
之后的 \n