您的位置:首页 > 编程语言 > Java开发

通用的日志记录器(java)

2014-04-28 10:46 441 查看
线程安全的java日志记录器

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicReference;

/**
*
* @author zhangshuang
*
*/
public class SyncFile {
private static String FILENAME ="";

private static String FILEDIR="";

private static final AtomicReference<SyncFile> instance = new AtomicReference<SyncFile>();

private String currentDate = SyncFile.getCurrentDate();

private File file = null;

private FileWriter fw = null;

private BufferedWriter bw = null;

private SyncFile(String dir, String name) {
SyncFile.FILEDIR = dir;
SyncFile.FILENAME = name ;
while(dir.endsWith("/")) {
dir = dir.substring(0, dir.length() - 1);
}
mkDir(dir);
String filePath = dir + "/" + name + "." + currentDate ;
file = new File(filePath);
try {
if(!file . exists()) {
file.createNewFile();
}
fw = new FileWriter(file, true);
bw = new BufferedWriter(fw);
} catch (Exception e) {
e.printStackTrace();
}

}

public static SyncFile getInstance(String dir, String name) {
if( instance .get() == null ) {
instance .compareAndSet(null, new SyncFile(dir, name));
}
return instance.get();
}

public static SyncFile getInstance() {
if( instance .get() == null ) {
instance.compareAndSet(null, new SyncFile(FILEDIR, FILENAME));
}
return instance.get();
}

public synchronized void write (String line) {
openBuffer() ;

line = line.endsWith("\n") ? line : line + "\n";
try {
if(line != null && line.trim() != ""){
bw.write(line);
bw.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}

private static void mkDir( String dir) {
File file = new File(dir);
mkDir(file);
}

/**
* <p>递归创建不存在的目录
* @param file
*/
private static void mkDir(File file){
if(file.getParentFile().exists()){
file.mkdir();
}else{
mkDir(file.getParentFile());
file.mkdir();
}
}

public static String getCurrentDate() {
return new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
}

private void openBuffer() {

if(!currentDate.equals(SyncFile.getCurrentDate()) || fw == null ||bw == null) {
if (!currentDate.equals(SyncFile.getCurrentDate())){
currentDate = SyncFile.getCurrentDate();
file = new File(FILEDIR + "/" + FILENAME + "." + currentDate);
}
close ();
try {
fw = new FileWriter(file , true);
bw = new BufferedWriter(fw);
} catch (IOException e) {
e.printStackTrace();
}
}

}

public void close() {
try {
if (bw != null) {
bw.close();
bw = null;
}

if (fw != null) {
fw.close();
fw = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
//        String a = "/data/logs/////";
//        while (a.endsWith("/")) {
//            a = a.substring(0 , a.length()-1);
//            System.out.println(a);
//        }
//        System.out.println("ok" + a);
mkDir("c:/2");
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: