java - append 到文件

标签 java io append fileoutputstream printwriter

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

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();
        }

    }

}

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

提前致谢。

最佳答案

PrintWriter#append不将数据 append 到文件中。相反,它使用 Writer 执行直接写入。您需要使用 append 标志声明您的 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 block 中。

关于java - append 到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16290160/

相关文章:

java - 键入 DefaultListModel 以避免强制转换

java - java中的正则表达式

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

linux - 如何解释 fio iops 日志文件?

python - 在 Python 中迭代 append 到字符串的有效方法?

javascript - 如何 append 到 Angular js中的json对象

Java Stream 接口(interface)映射函数参数类型

java - 无法更新 MySQL 中的数据库记录

c# - 在 .Net 中读取包含文本和二进制信息的文件

javascript - 无法在 dom 元素中看到 append 文本