package com.child.fileread;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class LogWriter {
private SimpleDateFormat dateFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
* 将信息记录到日志文件
*
* @param logFile 日志文件
* @param mesInfo 信息
* @throws IOException
*/
public void logMsg(File logFile, String mesInfo) throws IOException {
if (logFile == null) {
throw new IllegalStateException("logFile can not be null!");
}
Writer txtWriter = new FileWriter(logFile, true);
txtWriter.write(dateFormat.format(new Date()) + "\t" + mesInfo + "\n");
txtWriter.flush();
}
public static void main(String[] args) throws Exception {
final LogWriter logSvr = new LogWriter();
final File tmpLogFile = new File("d:/upload/text.txt");
if (!tmpLogFile.exists()) {
tmpLogFile.createNewFile();
}
Random random = new Random();
ScheduledExecutorService exec =
Executors.newScheduledThreadPool(1);
exec.scheduleWithFixedDelay(new Runnable() {
public void run() {
try {
logSvr.logMsg(tmpLogFile, String.valueOf(random.nextInt()) + "你好");
} catch (IOException e) {
System.out.println("logFile can not be null");
throw new RuntimeException(e);
}
}
}, 0, 1, TimeUnit.SECONDS);
}
}