package util;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FileWriterUtil {
private static Long fileSize = 1024*1024*Long.parseLong(ConfigCacheUtil.getInstance().getCache("fileSize"));
private static String fileSplitStr = ConfigCacheUtil.getInstance().getCache("fileSplitStr");
private static String fileBaseDir = ConfigCacheUtil.getInstance().getCache("fileBaseDir");
private static String fileTail = ".log";
/**
* @param logType 日志类型,可自行命名,暂定为alarm
* @param logContent 日志内容,要写的文件内容
*/
public static void writeLog(String logType,String logContent) {
FileWriter writer = null;
try {
String fileName = getLogFileName(logType);
File file = new File(fileName);
if(!file.exists()){
file.createNewFile();
}
writer = new FileWriter(fileName, true);
if(!logContent.endsWith("\\n")&&!logContent.endsWith("\r\n")&&!logContent.endsWith("\n")){
logContent = logContent + fileSplitStr;
}
writer.write(logContent);
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if(writer != null){
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//文件命名格式alarm20141212.1.log,注意,如果修改文件命名格式,需要修改文件名比较的Comparator
@SuppressWarnings("unchecked")
private static String getLogFileName(String logType) {
String dateStr = getDateFormat("yyyyMMdd", new Date());
final int startComPoint = logType.length()+9; //文件名称比较的起点,文件名称的前缀位数+日期的8位+.号的1位
String filePath = fileBaseDir+logType+"/"+dateStr+"/";//info20170731
File file = new File(filePath);
if(!file.exists()){
file.mkdirs();
}
File[] files = file.listFiles();
Arrays.sort(files, new CompratorByLastModified());
String lastFileName = filePath + logType + dateStr + ".1"+fileTail; //默认的日志文件名从1开始
if(files.length > 0){ //如果已经有日志文件,则取最后1个,并判断大小。如超过限制,另外生成一个文件;没有超过则使用最后1个
File lastFile = getLastFile(files,logType+dateStr+".*.log");
if(lastFile!=null&&lastFile.isFile()){
lastFileName = filePath+lastFile.getName();
if(lastFile.length()>=fileSize){
String lastLogFile_tag = lastFile.getName().substring(startComPoint).replace(fileTail, "");
int newLogFile_tag = Integer.parseInt(lastLogFile_tag)+1;
lastFileName = filePath + logType + dateStr + "."+newLogFile_tag+fileTail;
}
}
}
return lastFileName;
}
//比较器-按最后修改时间排序
private static class CompratorByLastModified implements Comparator<File>{
public int compare(File f1, File f2) {
long diff = f1.lastModified()-f2.lastModified();
if(diff>0){
return 1;
}
else if(diff==0){
return 0;
}
else {
return -1;
}
}
public boolean equals(Object obj){
return true;
}
}
//根据排好序的文件序列,取需要的文件名称
private static File getLastFile(File[] files,String regex){
File file = null;
if(files!=null){
int fileLength = files.length;
Pattern pattern = Pattern.compile(regex);
Matcher matcher = null;
for(int i=0;i<fileLength;i++){
file = files[fileLength-i-1];
String fileName = file.getName();
//此处加入规则校验,检查是否为日志文件
matcher = pattern.matcher(fileName);
if(matcher.matches()){
if(file.exists()&&file.isFile()){
break;
}
}
}
}
return file;
}
//格式化日期字符串
private static String getDateFormat(String pattern, Date date) {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
format.applyPattern(pattern);
return format.format(date);
}
public static void main(String[] args) {
getLogFileName("alarm");
}
}