我正在尝试编写一个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/