java-io流-合併多個檔案
此處以log0.txt和log1.txt合併為log.txt為例。
//建立一個檔案陣列來存放原始檔
File[] orfiles = new File[2];
orfiles[0] = new File(property+"\\log0.txt");//property為檔案路徑
orfiles[1] = new File(property+"\\log1.txt");
//建立輸出流
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(property+"\\log.txt")));
byte[] buffer = new byte[1024];
//因為我這塊是倆個日誌檔案,輸出日誌的時候是輪詢著輸出。一個日誌大小超過6M之後自動輸出到另一個日誌檔案。
//比較倆個檔案的大小。決定合併時輸出的前後順序。小的是最新日誌。
//比較大小,決定前後位置
if(log0.length()>log1.length()) {
//log1為最新日誌。此處可以用for迴圈實現。為了方便我此處未使用。
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(orfiles[0]));
int readcount;
while ((readcount = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, readcount);
}
inputStream.close();
BufferedInputStream inputStream1 = new BufferedInputStream(new FileInputStream(orfiles[1]));
int readcount1;
while ((readcount1 = inputStream1.read(buffer)) > 0) {
outputStream.write(buffer, 0, readcount1);
}
inputStream1.close();
outputStream.close();
}else {
//log0為最新日誌
BufferedInputStream inputStream1 = new BufferedInputStream(new FileInputStream(orfiles[1]));
int readcount1;
while ((readcount1 = inputStream1.read(buffer)) > 0) {
outputStream.write(buffer, 0, readcount1);
}
inputStream1.close();
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(orfiles[0]));
int readcount;
while ((readcount = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, readcount);
}
inputStream.close();
outputStream.close();
}