我写的Log文件贴上来用于以后备用和扩展
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Log {
/**
* LogType Case 0: uninitialized or reseted 1: console stream 2: file stream
*/
private static int logType = 0;
private static String filePath = "";
private static File file = null;
private static SimpleDateFormat timeSDF = null;
private static SimpleDateFormat daySDF = null;
public static void main(String args[]) {
Log.open(2);
Log.writeLine("hello!");
}
public Log() {
}
public static void open(int mLogType) {
timeSDF = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]");
daySDF = new SimpleDateFormat("yyyyMMdd");
switch (mLogType) {
case 0:
break;
case 1:
logType = 1;
break;
case 2:
openFileLog();
break;
default:
logType = 0;
}
}
public static void reset(int mLogType) {
open(mLogType);
}
public static void openFileLog() {
filePath = getFilePath();
file = new File(filePath);
if (file.exists() == false) {
try {
file.createNewFile();
} catch (IOException e) {
logType = 0;
return;
}
}
if (file == null) {
logType = 0;
return;
}
try {
System.setOut(new PrintStream(new FileOutputStream(file, true)));
} catch (FileNotFoundException e) {
logType = 0;
return;
}
logType = 2;
}
public static String getFilePath() {
File dir = new File("log");
if (dir.exists() == false) {
if (dir.mkdir() == false)
return null;
}
StringBuilder rtn = new StringBuilder(dir.getPath());
rtn.append("/");
rtn.append(daySDF.format(new Date()));
rtn.append(".log");
return rtn.toString();
}
public static void writeLine(String str) {
if (logType > 0) {
System.out.print(timeSDF.format(new Date()));
System.out.print(" ");
System.out.println(str);
}
}
public static void write(String str) {
if (logType > 0) {
System.out.print(timeSDF.format(new Date()));
System.out.print(" ");
System.out.print(str);
}
}
public static void writeLine() {
if (logType > 0) {
System.out.println();
}
}
}