使用java实现日志工具类分享
本文导语: 代码如下:package com.teligen.eos.teleCode; import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.util.Date; /** * 书写日志信息到指定的文件中 */public class WriteLogUtil { private static String rootPath = "D:\logs\"; /** * 将信息写到文...
package com.teligen.eos.teleCode;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
/**
* 书写日志信息到指定的文件中
*/
public class WriteLogUtil {
private static String rootPath = "D:\logs\";
/**
* 将信息写到文件中
* @param msg
*/
public static void writeMsgToFile(String msg) {
//删除之前的文件
delOldFile();
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(getFileName(),true);
Date today = new Date();
String time = String.valueOf(today.getHours()) + ":" + String.valueOf(today.getMinutes()) + " " + String.valueOf(today.getSeconds());
fileWriter.write("#" + time + "# [" + msg + "]" + "rn");
fileWriter.flush();
} catch (IOException e) {
System.out.println("### 写日志到文件异常 ### >>> " + e.getMessage());
e.printStackTrace();
} finally {
try {
fileWriter.close();
} catch (IOException e) {
System.out.println("### 关闭写日志的流异常 ### >>> " + e.getMessage());
e.printStackTrace();
}
}
}
/**
* 删除之前的日志文件
*/
private static void delOldFile() {
Date today = new Date();
int month = today.getMonth()+1;
month = month - 2;
if(month == -1) month = 11;
if(month == 0) month = 12;
String delPath = rootPath + String.valueOf(month) + "\";
File folder = new File(delPath);
if(folder.exists()) {
File[] files = folder.listFiles();
for(int i=0; i