我正在用Java(新開發人員)編寫應用程序,並試圖在日誌文件(日誌/ [日期] .txt)中保存消息和類似內容。我得到的問題是它每次都覆蓋,而不是將值附加到我的文件。Java - 僅記錄最新項目的日誌文件
這裏是我的代碼:
public void onMessage(String channel, String nick, String account, String hostname, String message) {
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss dd/MM/yyyy");
SimpleDateFormat sdfd = new SimpleDateFormat("dd/MM/yyyy");
Date now = new Date();
try {
/* Check if the logs folder exists */
File logdir = new File("logs/");
boolean result = true;
if (!logdir.exists()) {
try {
logdir.mkdir();
}catch(Exception e){
System.err.println("[ERROR] Could not make directory 'logs/'");
result = false;
}
}
/* Check if the log file exists */
File fcheck = new File("logs/" + sdfd.format(now).replace("/", "-") + ".txt");
if (!fcheck.exists()) {
try {
fcheck.createNewFile();
}catch (Exception e){
System.err.println("[ERROR] Could not make log file 'logs/" + sdfd.format(now).replace("/", "-") + ".txt'");
}
}
/* Write to file */
if (result) {
FileWriter file = new FileWriter("logs/" + sdfd.format(now).replace("/", "-") + ".txt");
PrintWriter write = new PrintWriter(file);
String entry = "[" + sdf.format(now) + "] [" + channel + "] " + nick + " (" + account + ") > " + message + "\n";
write.append(entry);
write.close();
file.close();
}else{
System.err.println("[ERROR] Could not save line to log file.");
}
}catch (Exception e){
System.err.println("[ERROR] Could not save line to log file.");
}
}
很抱歉,如果這是不是非常的清晰,但我還是學習Java。 正如你所看到的,我有write.append(entry);
--我認爲它會將\ n添加到我的日誌文件中,從而允許我保存並保存所有條目。
不相關的,但唉:重構文件名的創建,爲什麼你重新創建日誌? – 2014-10-27 14:00:18
一個建議,不要重新發明輪子,你可以使用log4j或java.util.Logger並讓它們處理文件......除非你想了解它是如何工作的,我鼓勵你在這些庫中獲得一些知識。 – 2014-10-27 14:03:46
對於['PrintWriter'構造函數](http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter(java.io.File)]的窗體(singnature) )你使用:「*如果文件存在,那麼它將被**截斷爲零大小**;否則,將創建一個新文件。」*「。 – 2014-10-27 14:13:42