自己创建记录运行程序的错误记录,以便在需要时查看,还是挺有意思的。
1.定义方法:
public class LogUtil {
//定义记录日志的方法
public static void Log(String msg){
try {
//指向一个日志文件
PrintStream out = new PrintStream(new FileOutputStream("log.txt",true));
//改变一个输出方向
System.setOut(out);
//日期当前时间
Date nowTime = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
String strTime = sdf.format(nowTime);
System.out.println(strTime+": "+msg);
} catch (
FileNotFoundException e) {
e.printStackTrace();
}
}
}
2.调用方法进行测试:
public static void main(String[] args) {
LogUtil.Log("调用了System的gc()方法,建议启动垃圾回收机制!");
}
3.测试结果,打开项目下的log.txt文件: