附加到文件 [英] Append to a File
问题描述
我试图写追加了系统的当前日期和时间到日志文件(也被通过批处理文件在我的电脑启动时运行)的Java程序。这里是我的code。
I am trying to write a java program that appends the current date and time of the system to a log file (that gets run by a batch file at my computer startup). Here's is my code.
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();
}
}
}
的问题是,它不追加:)到文件中。有人能指出这里有什么问题吗?
The problem is, it's not appending :) to the file. Can someone point out what is the problem here ?
先谢谢了。
推荐答案
<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#append%28java.lang.CharSequence%29\"相对=nofollow>的PrintWriter#追加不将数据追加到一个文件中。相反,它执行使用作家直接
。需要声明的写
的FileOutputStream
使用附加标志的构造函数:
PrintWriter#append does not append data to a file. Instead it performs a direct write
using the Writer
. You need to declare your FileOutputStream
constructor using an append flag:
f = new FileOutputStream("log.txt", true);
w = new PrintWriter(f); // autoflush not required provided close is called
的追加
仍然可以使用或方法更方便的是的println
这将不需要换行符是补充:
The append
method may still be used or more convenient is println
which will not require a newline character to be added:
w.println(dateFormat.format(date));
在的PrintWriter
构造函数的自动冲洗标志不是必需提供接近被调用。 关闭
应该出现在最后
块。
The autoflush flag in the PrintWriter
constructor is not required provided close is called. close
should appear in a finally
block.
这篇关于附加到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!