【问题标题】:Can't successfully add a newline when I append text to a file将文本附加到文件时无法成功添加换行符
【发布时间】:2015-08-04 16:39:38
【问题描述】:

我创建了一个应用程序,该应用程序在设备上创建了一个文件,该文件存储了大约 5 个值(双精度值)。我认为我正在成功写入文件,因为在写入文件后我会在设备上看到一条 toast 消息。

如果我尝试在命令中添加换行符,那么我永远不会看到 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]));在我的代码中,我可以查看这些值,因为我无法在文件系统上找到该文件。

【问题讨论】:

  • 请粘贴logcat的输出,即将Log.e("SOME_TAG", e.toString());添加到catch块中。
  • 您如何尝试添加换行符?
  • 我尝试在每次写入时将其附加: + "\r\n" 到字符串。我应该先这样做吗?我也尝试了行分隔符,但这没有用。 outputStreamWriter.append(String.format("%.2f", priceArray[i] + "\r\n"));也许当我读回它时,它会将它放入一个字符串中。我希望我能在资源管理器中找到该文件并打开它进行查看。

标签: java android save newline


【解决方案1】:

您应该正确格式化: outputStreamWriter.append(String.format("%.2f\n", priceArray[i]); 注意 %.2f 之后的 \n。

【讨论】:

  • 谢谢@krzdyn 我按照你说的做了,现在它成功地写入并给出了祝酒消息。现在我只需要正确读取文件。再次感谢!
猜你喜欢
  • 1970-01-01
  • 2022-01-20
  • 2018-07-29
  • 2018-05-05
  • 2015-11-25
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多