[英]Append to a File
我正在嘗試編寫一個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();
}
}
}
問題是,它沒有將:)附加到文件中。 有人可以指出這里有什么問題嗎?
提前致謝。
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
塊中。
PrintWriter
構造函數不使用用於決定是否附加到文件的參數。 它控制自動沖洗。
創建一個FileOutputStream
(可以控制是否附加到文件),然后將該流包裝在PrintWriter
。
try {
f=new FileOutputStream("log.txt", true);
w=new PrintWriter(f, true); // This true doesn't control whether to append
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.