我是新手編程並嘗試創建日誌文件。我編寫的代碼將信息和時間發送到文本文件。但每次我發送另一條消息時,它都會記錄以前的消息。我想有一個不是最新的消息和時間列表。嘗試使用java創建文本文件日誌
public void run() {
String message;
try {
while ((message = reader.readLine()) != null){
System.out.println("You voted " + message + " You the best") ;
BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));
out.append(message + "\n");
TimeZone tz = TimeZone.getTimeZone("UTC"); // or PST, MID, etc ...
Date now = new Date();
DateFormat df = new SimpleDateFormat (" yyyy.MM.dd hh:mm:ss ");
df.setTimeZone(tz);
String currentTime = df.format(now);
String timeStamp = new SimpleDateFormat().format(new Date());
FileWriter aWriter = new FileWriter("test.txt", true);
aWriter.write(currentTime + " " + "\n");
aWriter.flush();
aWriter.close();
out.write(message);
out.close();
everyoneMessage(message);
} // close while
}catch(Exception ex) {ex .printStackTrace();}
} // close run
}// close inner class
爲什麼不使用log4j? – Gleeb
查看java.util.logging.Logger,當你檢出結果時,slf4j – BevynQ
使用日誌庫(例如log4j),不要忘記將close語句放在'finally'塊中; –