废话就不多说了,直接进入主题:代码如下:
1.读取log或者txt文本信息
/**
* 读取log或者txt信息
*
* @param filePath
* @return
*/
public List<String> readLog(String filePath) {
List<String> list = new ArrayList<String>();
try {
FileInputStream is = new FileInputStream(filePath);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
try {
while ((line = br.readLine()) != null) {
if (line.equals(""))
continue;
else
list.add(line);
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("读取一行数据时出错");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件读取路径错误FileNotFoundException");
}
return list;
}
2.写入log或者txt文件内容
/**
* 新建log或者txt文件并写入内容
*
* @param filePath
* @param fileName
* @param msg
*/
public void createLog(String filePath, String fileName, String msg) {
PrintWriter logPrint = null;
try {
logPrint = new PrintWriter(
new FileWriter(filePath + fileName, true), true);
} catch (IOException e) {
(new File(filePath)).mkdir();
try {
logPrint = new PrintWriter(new FileWriter(filePath + fileName,
true), true);
} catch (IOException ex) {
logPrint = new PrintWriter(System.err);
writerErrorInfo(logPrint, ex, "无法打开日志文件:" + filePath + fileName);
}
}
writerLogInfo(logPrint, msg);
}
/**
* 将文本信息写入日志文件
*
* @param msg
* 日志内容
*/
private synchronized static void writerLogInfo(PrintWriter logPrint,
String msg) {
logPrint.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
.format(new Date())
+ " " + msg);
}
/**
* 将文本信息与异常写入日志文件
*
* @param e
* @param msg
*/
private synchronized static void writerErrorInfo(PrintWriter logPrint,
Throwable e, String msg) {
logPrint.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
.format(new Date())
+ " " + msg);
e.printStackTrace(logPrint);
}
注意的是:
filePath必须是这样的:“盘号://文件夹名称//”
fileName必须是这样的:test.txt 或者test.log