having a little bit of an issue. I am looping through a file where by I want to filter out a series of texts and concatenate them at the end of each loop, which then ultimately end up ordering i.e. during the loop phase it does the following:
String A = "A /n"
String A = "A /n U /n"
String A = "A /n U /n B /n"
etc...
The output will be
A
U
B
however i want it to be
A
B
U
I have so far done the following:
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();
}
Now this does output fine, however, with regards to the "otherStates", i want to get this in a numeric order, and the best way I know is using Collections, however this is for arrays. I am unsure how to go about modifying the "otherStates" part of the code to cater for an array that concatanetates the string and then be able to order them accordingly. Any ideas
答案 0 :(得分:1)
很难在没有输入文件数据的情况下提供正确的解决方案。试试下面的代码吧。至少它应该给你一些关于如何解决问题的想法
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 = "";
ArrayList<String> otherStates_duplicate = new ArrayList<>();
String ordered_new_string.;
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";
otherStates_duplicate.add(output);
}
Collections.sort(otherStates_duplicate); // Now this should have a sorted list
//if you need a string instead of an arraylist use code below in addition
for(String s:otherStates_duplicate){
ordered_new_string += s + "\n";
}
/*
I have not printed or stored the string ordered_new_string as it is not
clear to me what you want. print/write to a file and check
if ordered_new_string is what your required
*/
out.close();
}