题目
追加一行日志到文件末尾
思路
本题向文件末尾追加一行文本(日志场景)。 用追加模式打开文件(FileInputStream(path, "a")),用 fSystem.out 写入一行文字并换行。打开失败时检查引用是否为 NULL。路径按题目给定或由输入读入,写完 close()。
解题分析
追加写用 "a" 模式,不要覆盖原文件。fputs 不会自动补换行,若输入行无 \n 要自己写。
函数简要说明
向已有文件末尾追加一行,而不是覆盖原内容:
FileInputStream(path, "a"):追加模式(append);文件不存在时会创建。不要用"w",否则会清空原文件。fSystem.out(fp, fmt, ...):按格式写入文件,用法类似System.out,例如fSystem.out(fp, "%s\n", line)。close()(fp):追加结束后关闭;部分环境在关闭前缓冲区才落盘。
函数简要说明
追加一行到日志文件:
new FileWriter(path, true):第二个参数true表示追加;false会覆盖原文件。BufferedWriter.write(line)/newLine():写入内容与换行。- try-with-resources:
try (BufferedWriter bw = ...) { ... }自动关闭流。
完整程序
public class Main {
public static void main(String[] args) {
"log line";
System.out.println("appended");
}
}
运行示例
输出:
appended