- 性别
- 保密
- 积分
- 100
- 积分
- 351
- 精华
- 6
- 阅读权限
- 100
- 注册时间
- 2013-5-16
- 最后登录
- 2013-11-8
- 帖子
- 43
- 性别
- 保密
|
本帖最后由 sky_yx 于 2015-12-30 14:09 编辑
以写日志为例:
示例代码------------------------------------------------------------------------------------
package com.moshi.singleton;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class logmagage {
private static PrintWriter out;
private final static String filename="G://log.txt";//设置日志问题路径
//唯一实例 logmagage
private static logmagage logmagage;
private logmagage(){
outinit();
}
public static void outinit(){
if(out==null){
try {
out=new PrintWriter(new FileWriter(filename,true),true);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.print("无法打开日志文件");
e.printStackTrace();
out=null;
}
}
}
public static synchronized void log(String msg){
if(logmagage==null||out==null){logmagage=new logmagage();}
if(out!=null){
out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+":"+msg);
}
}
public static void destory(){
if(out!=null)out.close();
}
}
//客户端调用
package com.moshi.singleton;
public class logclient {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
logmagage.log("javaweb程序设计");//写入日志
}
}
|
|