【问题标题】:Append to a File附加到文件
【发布时间】:2013-04-23 19:10:24
【问题描述】:

我正在尝试编写一个 java 程序,将系统的当前日期和时间附加到一个日志文件(在我的计算机启动时由批处理文件运行)。这是我的代码。

public class LogWriter {

    public static void main(String[] args) {

        /* open the write file */
        FileOutputStream f=null;
        PrintWriter w=null;

        try {
            f=new FileOutputStream("log.txt");
            w=new PrintWriter(f, true);
        } catch (Exception e) {
            System.out.println("Can't write file");
        }

        /* replace this with your own username */
        String user="kumar116";
        w.append(user+"\t");

        /* c/p http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/ */
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        w.append(dateFormat.format(date)+'\n');

        /* close the write file*/
        if(w!=null) {
            w.close();
        }

    }

}

问题是,它没有将 :) 附加到文件中。有人能指出这里有什么问题吗?

提前致谢。

【问题讨论】:

    标签: java io append fileoutputstream printwriter


    【解决方案1】:

    PrintWriter 构造函数不采用参数来决定是否附加到文件。它控制自动刷新。

    创建一个FileOutputStream(可以控制是否附加到文件),然后将该流包装在您的PrintWriter中。

    try {
        f=new FileOutputStream("log.txt", true);
        w=new PrintWriter(f, true);  // This true doesn't control whether to append
    }
    

    【讨论】:

      【解决方案2】:

      PrintWriter#append 不会将数据附加到文件中。相反,它使用Writer 直接执行write。您需要使用附加标志声明 FileOutputStream 构造函数:

      f = new FileOutputStream("log.txt", true);
      w = new PrintWriter(f); // autoflush not required provided close is called
      

      append 方法仍然可以使用,或者更方便的是 println,它不需要添加换行符:

      w.println(dateFormat.format(date));
      

      如果调用了 close,则不需要 PrintWriter 构造函数中的 autoflush 标志。 close 应该出现在 finally 块中。

      【讨论】:

      • 你应该在 Writer 之后添加一个`。事实上,它看起来相当糟糕:Writer. You need to declare your FileOutputStream`
      • 感谢您的回答。
      猜你喜欢
      • 1970-01-01
      • 2013-05-13
      • 2010-09-27
      • 2016-12-12
      • 2019-04-22
      • 2015-05-25
      • 2021-05-08
      • 1970-01-01
      相关资源
      最近更新 更多