【发布时间】:2016-01-03 02:35:39
【问题描述】:
有点问题。我正在循环一个文件,我想过滤掉一系列文本并在每个循环结束时将它们连接起来,然后最终排序,即在循环阶段它执行以下操作:
String A = "A /n"
String A = "A /n U /n"
String A = "A /n U /n B /n"
等等……
输出将是
一个
U
B
我希望它是这样的
一个
B
U
到目前为止,我已经完成了以下工作:
public static void organiseFile() throws FileNotFoundException {
ArrayList<String> lines = new ArrayList<>();
ArrayList<String> order = new ArrayList<>();
String directory = "C:\\Users\\xxx\\Desktop\\Files\\ex1";
Scanner fileIn = new Scanner(new File(directory + "_ordered.txt"));
PrintWriter out = new PrintWriter(directory + "_orderesqsd.txt");
String otherStates = "";
while (fileIn.hasNextLine() == true) {
lines.add(fileIn.nextLine());
System.out.println("Organising...");
}
Collections.sort(lines);
for (String output : lines) {
if (output.contains("[EVENT=agentStateEvent]")) {
out.println(output + "\n");
out.println(otherStates + "\n");
otherStates = "";
}
else {
otherStates += output+ "\n";
}
out.close();
}
现在这确实输出很好,但是,关于“otherStates”,我想按数字顺序得到它,我知道的最好的方法是使用集合,但是这是用于数组的。我不确定如何修改代码的“otherStates”部分来满足连接字符串的数组,然后能够相应地对它们进行排序。任何想法
【问题讨论】:
-
您的问题非常不清楚 - “我想按特定顺序得到这个”根本无法解释您想要什么顺序。为什么您将
otherStates收集为单个字符串,而不是某种集合?如果您想重新排序,请将所有元素收集为一个集合,对它们进行排序,然后然后将它们连接在一起... -
这是我苦苦挣扎的地方。我知道需要将 otherStates 从字符串更改为数组,以便我可以使用 collections.sort 对其进行排序。我有一个名为“order”的数组,但是我不能简单地将“otherStates”替换为“order”。
-
您没有任何数组。你有 ArrayLists。他们不是一回事。但是您可以为
otherStates创建第三个 ArrayList 并添加到其中而不是使用字符串连接 - 是什么阻止您这样做?
标签: java string arraylist collections