ランダムストリームRandomAccess Fileを使ってファイル指定の内容を削除します。
4461 ワード
あるサービスのログファイルが指定サイズに達したら、ログファイルの前の何行を削除しますか?後に新しいログを追加します。
/**
* @Title: removeFileLine
* @Description: TODO( n )
* @param: @param file
* @param: @param lineNum
* @param: @throws IOException
* @return: void
* @throws
*/
public void removeFileLine(File file, int lineNum) throws IOException {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(file, "rw");
// Initial write position.
// , ,
long writePosition = raf.getFilePointer();
for (int i = 0; i < lineNum; i++) {
String line = raf.readLine();
if (line == null) {
break;
}
}
// Shift the next lines upwards.
// ,
long readPosition = raf.getFilePointer();
// ,
byte[] buff = new byte[1024];
int n;
while (-1 != (n = raf.read(buff))) {
raf.seek(writePosition);
raf.write(buff, 0, n);
readPosition += n;
writePosition += n;
raf.seek(readPosition);
}
raf.setLength(writePosition);
} catch (IOException e) {
logger.error("readAndRemoveFirstLines error", e);
throw e;
} finally {
try {
if (raf != null) {
raf.close();
}
} catch (IOException e) {
logger.error("close RandomAccessFile error", e);
throw e;
}
}
}
/**
* @Title: appendContentToFile
* @Description: TODO( )
* @param: @param file
* @param: @param content
* @param: @throws IOException
* @return: void
* @throws
*/
public static void appendContentToFile(File file, String content) throws IOException {
RandomAccessFile randomFile = null;
try {
// ,
randomFile = new RandomAccessFile(file, "rw");
// ,
long fileLength = randomFile.length();
// 。
randomFile.seek(fileLength);
randomFile.writeBytes(content);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
randomFile.close();
randomFile = null;
}
}
}
/**
* @Title: checkFileInSize
* @Description: TODO( )
* @param: @param file
* @param: @param limitSize
* @param: @return
* @return: boolean
* @throws
*/
private boolean checkFileInSize(File file, Long limitSize) {
return file.length() <= limitSize;
}
以上が上記の需要の方法です。上記の方法を統合して需要を完成します。@Component
@SuppressWarnings("restriction")
@PropertySource("classpath:/config/ivg.properties")
public class AppStartupListener implements ApplicationRunner {
@Value("${log.startup.path}")
private String logPath;//
@Value("${log.startup.output.statement}")
private String outputStatement;//
@Value("${log.startup.limit.size}")
private Long limitSize;// ,eg:50M:50*1024*1024 = 52428800
@Value("${log.startup.remove.line}")
private int removeLineNum;//
private void initLog() {
logger.info("*** ***");
//
File file = null;
try {
file = new File(logPath);
if (!file.exists() || !file.isFile()) {
logger.info("file is not exist,creating " + logPath + " now...");
file.createNewFile();
}
StringBuilder sb = new StringBuilder(outputStatement);
SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss");
String date = sdf.format(new Date());
String outputLog = sb.append(date).append("\r
").toString();
//
while (!checkFileInSize(file, limitSize)) {
//
removeFileLine(file, removeLineNum);
}
// log
appendContentToFile(file, outputLog);
} catch (FileNotFoundException e) {
logger.error("StartupLog Listener error,{}", e);
} catch (IOException e) {
logger.error("StartupLog Listener error,{}", e);
}
}
}