线程安全的JAva日志类

暂时是学习吧,但是先记录下,就是单例类,创建文件,写文件。是线程安全的。

package myPackage;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

public class WriteFile {
private static WriteFile writeFile;

File statText;
private static FileWriter MyWriter;

public WriteFile(){
	final String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
	try {
		//What ever the file path is.
		        MyWriter = new FileWriter(date +".txt");
		    } catch (IOException e) {
		        System.err.println("Problem writing to the file statsTest.txt");
		    }
}

public static synchronized WriteFile GetInstance(){
	if (null == writeFile) {
		writeFile = new WriteFile();
	}
	return writeFile;
}

public static synchronized void MyLog(String string){
	try {
		MyWriter.append("\n\r" + string + "\n\r");
		MyWriter.flush();
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}
}

}



测试类:

package myPackage;

public class LogTest {
public static void main(String[] strings){
	WriteFile writeFile = WriteFile.GetInstance();
	for (int i = 0; i < 10; i++) {
		writeFile.MyLog("a u kidding me?");
	}
	
}
}


问题是 文件创建成功了,但是没有内容写入。

你可能感兴趣的:(Java)