本篇log日志类的实现,简单采用了单例模式+IO流技术实现。
package cn.activemq.validate; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; /** * 自定义缓存日志类 */ public class LqLog { private static volatile LqLog instance = null; private BufferedOutputStream bos; private SimpleDateFormat sdf; private LqLog(BufferedOutputStream bos, SimpleDateFormat sdf) { this.bos = bos; this.sdf = sdf; } public static LqLog getInstance() { if (instance == null) { synchronized (LqLog.class) { if (instance == null) { File file = new File("D:\\lq.txt"); try { if (!file.exists()) { file.createNewFile(); } FileOutputStream fos = new FileOutputStream(file,true); BufferedOutputStream bos = new BufferedOutputStream(fos); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); instance = new LqLog(bos,sdf); } catch (IOException e) { e.printStackTrace(); } } } } return instance; } //写日志 public void writeLog(String log){ try { String content = sdf.format(new Date())+" "+log; bos.write(content.getBytes()); bos.write("\r\n".getBytes()); bos.flush(); } catch (IOException e) { e.printStackTrace(); } } //关闭io public void close(){ if (bos!=null){ try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } } }