我有这个文本文件,我喜欢根据 HC 和 P3 对中的 HC 进行排序
这是我要排序的文件(avgGen.txt):
7686.88,HC
20169.22,P3
7820.86,HC
19686.34,P3
6805.62,HC
17933.10,P3
然后我想要的输出到新的文本文件(output.txt)是:
6805.62,HC
17933.10,P3
7686.88,HC
20169.22,P3
7820.86,HC
19686.34,P3
如何对文本文件中的 HC 和 P3 对进行排序,其中 HC 始终出现在奇数索引中,P3 出现在偶数索引中,但我希望根据 HC 值升序排序?
这是我的代码:
public class SortTest {
public static void main (String[] args) throws IOException{
ArrayList<Double> rows = new ArrayList<Double>();
ArrayList<String> convertString = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("avgGen.txt"));
String s;
while((s = reader.readLine())!=null){
String[] data = s.split(",");
double avg = Double.parseDouble(data[0]);
rows.add(avg);
}
Collections.sort(rows);
for (Double toStr : rows){
convertString.add(String.valueOf(toStr));
}
FileWriter writer = new FileWriter("output.txt");
for(String cur: convertString)
writer.write(cur +"\n");
reader.close();
writer.close();
}
}
请帮忙。
最佳答案
当您从输入文件中读取时,您实际上丢弃了字符串值。为了您的目的,您需要保留这些字符串值并将它们与相应的 double 值相关联。
你可以
- 将 double 值和字符串值包装到一个类中,
- 使用该类而不是单独使用 double 值创建列表
- 然后使用 Comparator 根据类的 double 值对列表进行排序,或者使类实现 Comparable 接口(interface)。
- 打印出 double 值及其关联的字符串值,它们封装在一个类中
下面是一个例子:
static class Item {
String str;
Double value;
public Item(String str, Double value) {
this.str = str;
this.value = value;
}
}
public static void main (String[] args) throws IOException {
ArrayList<Item> rows = new ArrayList<Item>();
BufferedReader reader = new BufferedReader(new FileReader("avgGen.txt"));
String s;
while((s = reader.readLine())!=null){
String[] data = s.split(",");
double avg = Double.parseDouble(data[0]);
rows.add(new Item(data[1], avg));
}
Collections.sort(rows, new Comparator<Item>() {
public int compare(Item o1, Item o2) {
if (o1.value < o2.value) {
return -1;
} else if (o1.value > o2.value) {
return 1;
}
return 0;
}
});
FileWriter writer = new FileWriter("output.txt");
for(Item cur: rows)
writer.write(cur.value + "," + cur.str + "\n");
reader.close();
writer.close();
}
关于java - 如何从文本文件排序并写入另一个文本文件Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38551524/