gpt4 book ai didi

java - 将字符串写入文本文件

转载 作者:行者123 更新时间:2023-12-01 07:05:32 26 4
gpt4 key购买 nike

我正在将日志保存到 SD 卡上的 .txt 文件中,但是一旦保存了两行,它就会覆盖它并重新开始?

这是我的代码:

public static String getTimestamp() {
try {

SimpleDateFormat dateFormat = new SimpleDateFormat("MMMdd HH:mm:ss", Locale.getDefault());
String currentTimeStamp = dateFormat.format(new Date()); // Find todays date

return currentTimeStamp;
} catch (Exception e) {
e.printStackTrace();

return null;
}
}

public static void writeToLog(Context context, String string) {
String text = getTimestamp() + " " + string;
// ONLY SAVES TWO LINES
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(logFile, true)));
out.println(text);
out.close();
} catch (IOException e) {
Log.d(Constants.APP_NAME, e.toString());
}
}

一旦您在恢复中挂载/data,/sdcard 和/data/media/0 中的日志文件就会显示完整的日志历史记录,但设备开机时不会显示

最佳答案

您可以简单地使用 FileWriter没有其他作家的束缚。请务必调用 flush(),因为这可确保将所有缓冲内容写入文件。
如果这仍然不起作用,请检查错误输出。

public static void writeToLog(Context context, String string) {
String text = getTimestamp() + " " + string + "\n"; //newline here

Writer out;
try {
out = new FileWriter(logFile, true);
out.append(text);
out.flush(); //ensure that all buffered characters are written to the target
} catch (IOException e) {
Log.d(Constants.APP_NAME, e.toString());
} finally {
if (out != null) {
out.close(); //ensure writer is closed
}
}
}

关于java - 将字符串写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25597215/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com