有一点问题。我已经成功输出了一个基于时间戳顺序的文件,但是,如果时间戳相同,我还试图按字母顺序添加另一个条件。
例如:
[TIMESTAMP = 12:30] [EVENT = B]
[TIMESTAMP = 12:30] [EVENT = U]
[TIMESTAMP = 12:30] [EVENT = A]
我希望它输出
[TIMESTAMP = 12:30] [EVENT = A]
[TIMESTAMP = 12:30] [EVENT = B]
[TIMESTAMP = 12:30] [EVENT = U]
我目前的代码是:
package Organiser;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Organiser {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> lines = new ArrayList<>();
String directory = "C:\\Users\\xxx\\Desktop\\Files\\ex1";
Scanner fileIn = new Scanner(new File(directory + ".txt"));
PrintWriter out = new PrintWriter(directory + "_ordered.txt");
while (fileIn.hasNextLine() == true) {
lines.add(fileIn.nextLine());
Collections.sort(lines);
System.out.println("Reading...");
}
for (String output : lines) {
out.println(output + "\n");
}
out.close();
System.out.println("Complete - See " + directory + "_ordered.txt");
}
}
任何想法
编辑:这仅适用于样本数据,我只希望在时间戳相同时发生这种情况,否则,它会根据时间戳进行相应的排序。
示例文件:
答案 0 :(得分:1)
每次添加一行时都不应对Collection
进行排序!将Collections.sort(lines);
放在while循环
结果代码应该已经完成了这个诀窍......我已经在我的系统上测试了它并且它有效了!
答案 1 :(得分:0)
默认情况下应该会发生。 (因为&#39;&#39; B&#39;&#39;&#39; A&#39;)
public static void main(String[] args) {
ArrayList<String> lines = new ArrayList<>();
lines.add("[TIMESTAMP = 12:30][EVENT=B]");
lines.add("[TIMESTAMP = 12:30][EVENT=A]");
lines.add("[TIMESTAMP = 12:30][EVENT=U]");
// unsorted
System.out.println(lines);
// default sorting of Strings will sort A before U
Collections.sort(lines);
System.out.println(lines);
}