【问题标题】:PrintWriter--No Output?PrintWriter——没有输出?
【发布时间】:2014-12-19 08:31:00
【问题描述】:

编辑:已修复!正在覆盖文件而不是附加到文件。

在使用前尝试使用 PrintWriter 向日志文件添加“标题”似乎有点问题,以便我的程序知道它不仅仅是一个随机文本文件。字段 output_file 指的是记录器初始化函数用于设置日志文件的参数,而 log_file 是(全局和静态)日志记录类的静态文件字段。打开日志文件检查错误后,没有标题。使用同样由 PrintWriter 执行的日志记录功能,可以提供正确的输出。难道我做错了什么? (我知道我正在重新发明轮子,因为 Java 的日志记录 API 已经存在,但我正在进行学习练习。)

//After testing to make sure the file specified does not exist
log_file=output_file; 
output_file.createNewFile();
PrintWriter pw=new PrintWriter(log_file);
pw.println("**[PROGRAM_NAME Log]**");
pw.flush();
pw.close();
isInitialized=true;

编辑:该文件绝对是可写的,否则记录器本身将无法工作。此外,对于那些想知道的人,记录某些内容的代码如下(与编写标头 AKA new PrintWriter(log_file); 的一般方法相同)

PrintWriter pw = new PrintWriter(log_file);
pw.print("[INFO:] " + sdf.format(new Date())); //The variable sdf is a date formatter for timestamps.
pw.println(" " + message);
pw.close();

【问题讨论】:

  • 您似乎从log_file 登录到PrintWriter,但实际文件是从output_file 创建的(createNewFile())...这是正确的吗?
  • @ochi 但两个变量引用同一个对象。
  • -hard disk-文件是由createNewFile()创建的,是的,但是log_file和output_file在这里本质上是一样的。 (log_file=output_file;)
  • 您说日志记录也是由 PrintWriter 执行的。您是否也使用new PrintWriter(log_file)
  • 你能在写任何东西之前尝试if (!log_file.setWritable(true)) throw new Exception("cannot write to file");并将结果添加到你的帖子中吗?

标签: java


【解决方案1】:

documentation for PrintWriter 说:

file - 用作此 writer 目标的文件。如果文件 存在,那么它将被截断为零大小;否则,一个新文件 将被创建。输出将被写入文件并且是 缓冲。

因此,每次使用 new Printwriter(log_file) 时,实际上都是在截断文件,擦除其中的所有内容,然后重新开始。

当然,这意味着,一旦您开始记录,标题数据就会被删除。

如果你想追加到文件,而不是每次都删除它,你需要用append选项打开FileOutputStream,然后在上面打开PrintWriter它。

    try ( 
        FileOutputStream os = new FileOutputStream(log_file, true);
        PrintWriter pw = new PrintWriter(os);
    ) {
        pw.println("Your log line here");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }

(请注意,使用 try-with-resources 会在使用完成后自动关闭文件。当然,您可以保持打开状态直到完成日志记录。这只是一个示例。)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 2018-12-09
    相关资源
    最近更新 更多