版权声明:有问题可以大家一起交流学习! https://blog.csdn.net/laonayonghaifeisi/article/details/53243104
package tqm.util;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 文件日志处理工具类,提供了写入和读出方法
*
* @author tianming
*
*/
public class TxtLogUtil {
private static String path = "C:" + File.separator;//日志文件存放路径地址 可以随意修改
/**
* 文件日志记录
*
* @param content 写入内容
* @param fileName 日志文件名称
*/
public static void record(String content, String fileName) {
// //处理文件夹不存在的情况
File destDir = new File(path);
if (!destDir.exists()) {
destDir.mkdirs();
}
File file = new File(path + "\\" + fileName); //生成日志文件路径和文件名
if (file.exists() == false) { //判断文件是否存在,不存在则创建
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new FileOutputStream(file, true));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss ");
String time = sdf.format(new Date());
dos.write((time + " " + content + "\n").getBytes());
// dos.writeUTF(content + time + "\r\n");
// dos.writeUTF("------------------------------------------------------------------------------------------------------\r\n\r\n");
dos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
dos = null;
}
}
}
/**
* 正序读取txt文件的内容
*
* @param fileName 想要读取的文件名称
* @return 返回文件内容
*/
public static String txtRead(String fileName) {
File file = new File(path + File.separator + fileName); //日志文件路径和文件名
String result = ""; //返回读取文件内容
if (!file.exists()) {
result = "当前读取文件不存在";
} else {
try {
FileInputStream infile = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(infile, "utf-8"));//构造一个BufferedReader类来读取文件
String s = null;
while ((s = br.readLine()) != null) {//使用readLine方法,一次读一行
result = result + "\n" + s;
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
public static void main(String[] args) {
/**
* 测试文件
*/
String file = "定时器日志.txt";
String contentString = "定时器日志定时器日志定时器日志定时器日志";
TxtLogUtil.record(contentString, file);
System.err.println(TxtLogUtil.txtRead(file));
}
}