java向日志文件中寫入日誌
程式碼如下:
/**
*
* @param path
* path:儲存日誌檔案路徑
* @param content
* content:日誌內容
*/
public static void writeFile(String path, String content) {
File writefile;
try {
// 通過這個物件來判斷是否向文字檔案中追加內容
// boolean addStr = append;
writefile = new File(path);
// 如果文字檔案不存在則建立它
if (!writefile.exists()) {
writefile.createNewFile();
writefile = new File(path); // 重新例項化
}
FileOutputStream fw = new FileOutputStream(writefile,true);
Writer out = new OutputStreamWriter(fw, "utf-8");
out.write(content);
String newline = System.getProperty("line.separator");
//寫入換行
out.write(newline);
out.close();
fw.flush();
fw.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
// 獲取當前時間
public static String getCurrentYYYYMMDDHHMMSS() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
Date currTime = new Date();
String thisTime = new String(formatter.format(currTime));
return thisTime;
}
public static void main(String[] args) {
String logpath="E:/001.log";
String content = TransString.getCurrentYYYYMMDDHHMMSS() + " ****************************************進件處理開始****************************************";
writeFile(logpath, content);
content = TransString.getCurrentYYYYMMDDHHMMSS() + " 生成.spl的路勁為:" ;
writeFile(logpath, content);
writeFile(logpath,"dftyuiop[");
writeFile(logpath,"dftyuiop[");
}