[英]sort the file contents in ascending and descending order
我想根据增加的时间戳和降低的严重性对下面的日志文件进行排序。下面是我的Input.txt,我想将输出写到另一个文件中。附上我的Java代码。请建议解决此问题
[2015-11-19 10:33:54.934+0000] [HOST1] [INFO] [CLASS1] [MESSAGE1 something]
[2015-11-19 10:31:55.128+0000] [HOST2] [ERROR] [CLASS2] [MESSAGE2 random]
[2015-11-19 10:31:55.128+0000] [HOST3] [INFO] [CLASS6] [MESSAGE5 from another host]
[2015-11-19 10:37:55.246+0000] [HOST2] [WARN] [CLASS9] [MESSAGE9 again]
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
public class SortLogFile {
public static void main(String[] args) throws IOException {
BufferedReader reader = null;
PrintWriter outputStream = null;
ArrayList<String> rows = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader("Input.txt"));
outputStream = new PrintWriter(new FileWriter("Output.txt"));
String file;
while ((file = reader.readLine()) != null) {
rows.add(file);
}
Collections.sort(rows);
String[] strArr = rows.toArray(new String[0]);
for (String cur : strArr)
outputStream.println(cur);
} finally {
if (reader != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
创建一个类来代表每一行。 此类必须具有两个属性(日期和严重性)。 对于严重性,最好使用带有值的枚举,以便进行比较。 将所有对象添加到列表中并对其进行排序。
list.sort((a, b) -> {
if (a.getData().equals(b.getData())) {
return a.getSeverity().compareTo(b.getSeverity);
} else {
return a.getData().compareTo(b.getData());
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.