package nc.itf.mm.mes.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class MESLooger {
private static String fileLoggerPath = "E://MESLooger//logger.txt";
public static void main(String[] args) throws IOException {
StringBuffer sb = new StringBuffer();
sb.append("你好sss");
sb.append("\r\n");
sb.append("sbsvss");
writeTxtFile(sb.toString());
}
/**
* 写入日志信息
* @param errorInfo
*/
public static void writeTxtFile(String errorInfo) {
FileWriter fw = null;
try {
File file = new File(fileLoggerPath);
if (!file.exists()) {
File dir = new File(file.getParent());
dir.mkdirs();
file.createNewFile();
}else{
// FileOutputStream testfile = new FileOutputStream(fileLoggerPath);
// testfile.write(new String("").getBytes());
long fileSize = getFileSize(file);
long maxsiez = 52428800;//设定50M
if(maxsiez<=fileSize){
FileWriter fileWriter =new FileWriter(file);
fileWriter.write("");
fileWriter.flush();
fileWriter.close();
}
}
String str = readTxtFile(new File(fileLoggerPath));
fw = new FileWriter(fileLoggerPath);
if (str.length() < 1) {
fw.write(errorInfo);
} else {
fw.write(str + "\r\n" + errorInfo);
}
fw.close();
} catch (IOException e) {
e.printStackTrace();
try {
fw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
/*
* 获取文件大小的方法02:
* 通过FileChannel类来获取文件大小,这个方法通常结合输入流相关,
* 因此可以用于文件网络传输时实时计算文件大小;
* */
private static long getFileSize(File file) throws IOException {
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
return fc.size();
}
/**
* 读取原文件内容
* @param f
* @return
* @throws IOException
*/
public static String readTxtFile(File f) throws IOException {
String strs = "";
try {
@SuppressWarnings("resource")
FileReader read = new FileReader(f);
StringBuffer sb = new StringBuffer();
char ch[] = new char[1024];
int d = read.read(ch);
while (d != -1) {
String str = new String(ch, 0, d);
sb.append(str);
d = read.read(ch);
}
strs = sb.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return strs;
}
}
日志文件工具类
最新推荐文章于 2024-05-21 10:23:42 发布