单例模式之应用示例———编制日志类

  编制日志类。一般来说,应用程序都有日志文件,记录一些执行信息。在windows系统下,无论多次双击记事本文件,都只会出现一个窗口。

此功能正是利用单例对象来实现的。

不多说上代码:

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

public class FileLogger
{
private String path="D:/IDEA plugins/log.txt";//目的路径
private FileOutputStream out=new FileOutputStream(path,true);
// 上面的true意为 out从日志文件尾部开始添加纪录!重启后新日志自动追加到末尾,原信息不变!
private FileLogger()throws Exception //日志类
{
System.out.println("这是一个新实例!");
}
private static class My //单例模式 静态 内部
{
private static FileLogger fileLogger;

static
{
try
{
fileLogger = new FileLogger();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
public static FileLogger getFileLogger() //外部引用类,获取内部信息
{
return My.fileLogger;
}
// 文本的输入
public void write(String msg)
{
try
{
Calendar c=Calendar.getInstance();
int y=c.get(Calendar.YEAR);
int m=c.get(Calendar.MONTH);
int d=c.get(Calendar.DAY_OF_MONTH);
int hh=c.get(Calendar.HOUR);
int mm=c.get(Calendar.MINUTE);
int ss=c.get(Calendar.SECOND);

String strTime="";
strTime= strTime.format("time:%d-%02d-%02d %02d-%02d-%02d\r\n",y,m,d,hh,mm,ss);
String strContent="content:\r\n"+msg+"\r\n";

byte buf[]=strTime.getBytes("gbk");//设置编码方式
out.write(buf);
buf=strContent.getBytes("gbk");
out.write(buf);//此write非上面方法名write,此是(FileOutoutStream) out 的子方法
out.flush();
} catch (Exception e)
{
e.printStackTrace();
}
}
public void close()
{
try
{
out.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
下面编写一个测试类:
public class itsTest
{
public static void main(String[] args)
{
// 获得日志单例对象
FileLogger obj=FileLogger.getFileLogger();
obj.write("hello!");
obj.write("nihao!");
obj.write("利好刘!");
obj.close();
System.out.println("结束!");
}
}

运行:

这是一个新实例!
结束!

Process finished with exit code 0

目的文件已成功生成!

转载于:https://www.cnblogs.com/Mark-blog/p/8578471.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值