Here is the Java code to combine the same name log files in two folders into a new txt file in date order:
import java.io.*;
import java.text.*;
import java.util.*;
public class MergeLogs {
public static void main(String[] args) throws Exception {
// 输入源文件夹路径和目标文件路径
String sourceFolder1 = "path/to/source/folder1";
String sourceFolder2 = "path/to/source/folder2";
String destinationFile = "path/to/destination/file.txt";
// 获取源文件夹1中所有的log文件
File folder1 = new File(sourceFolder1);
File[] listOfFiles1 = folder1.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".log");
}
});
// 获取源文件夹2中所有的log文件
File folder2 = new File(sourceFolder2);
File[] listOfFiles2 = folder2.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".log");
}
});
// 将两个文件夹中所有的log文件放在一个数组中
File[] listOfFiles = new File[listOfFiles1.length + listOfFiles2.length];
System.arraycopy(listOfFiles1, 0, listOfFiles, 0, listOfFiles1.length);
System.arraycopy(listOfFiles2, 0, listOfFiles, listOfFiles1.length, listOfFiles2.length);
// 对log文件按日期进行排序
Arrays.sort(listOfFiles, new Comparator() {
public int compare(File f1, File f2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
try {
Date d1 = sdf.parse(f1.getName().substring(0, 8));
Date d2 = sdf.parse(f2.getName().substring(0, 8));
return d1.compareTo(d2);
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
});
// 将log文件中的内容拼接到目标文件中
BufferedWriter bw = new BufferedWriter(new FileWriter(destinationFile));
for (File file : listOfFiles) {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
br.close();
}
bw.close();
System.out.println("Logs merged successfully!");
}
}
In the
code, you first need to enter the source folder 1, source folder 2, and destination file path. It then takes all the log files in source folders 1 and 2 through the File class and the FilenameFilter interface and puts them in an array. The log files are then sorted by date using the Arrays.sort method and the Comparator interface. Finally, the BufferedWriter class is used to concatenate the contents of the log file into the object file and close the file stream. The message "Logs merged successfully!" is displayed. .