【发布时间】:2020-04-08 01:12:23
【问题描述】:
我有一个 CSV 文件,每行格式为:20 个字符字符串、10 个字符字符串、4 个字符字符串和一个双精度字符。
目标是读取文件并将信息存储到列表集合中。
然后使用比较器对第 3 列和第 1 列进行排序。
我想知道如何对它们进行排序,以及是否有更简单的方法。理想情况下,印刷品会用
之类的东西隔开System.out.printf("%-20s%-10s%-4s%10s%n", Result.get(0), Result.get(1), Result.get(2), Result.get(3));
我尝试过,但如果不需要“System.out.println(CSVtoArrayList(Line));”就无法显示线。我当前的代码:
public static void main(String[] args) {
BufferedReader Buffer = null;
try {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter file name: ");
String input1 = scanner.nextLine();
String Line;
Buffer = new BufferedReader(new FileReader(input1));
while ((Line = Buffer.readLine()) != null) {
System.out.println(CSVtoArrayList(Line));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (Buffer != null) Buffer.close();
} catch (IOException Exception) {
Exception.printStackTrace();
}
}
}
public static ArrayList<String> CSVtoArrayList(String CSV) {
ArrayList<String> Result = new ArrayList<String>();
if (CSV != null) {
String[] splitData = CSV.split("\\s*,\\s*");
for (int i = 0; i < splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() == 0)) {
Result.add(splitData[i].trim());
}
}
}
return Result;
}
这当前打印出如下内容:
Enter file name:
comma.txt
[frist movei, Bob, 1999, 24.98]
[first mobie, Steve, 1999, -345.67]
[first movie, Pam, 1999, 0.00]
[other moive, Sam, 1562, -42.16]
[something, Sue, 8951, 224.62]
【问题讨论】:
-
“将信息存储到列表集合中” 我认为没有尝试这样做。您正在询问如何对列表进行排序,但您甚至还没有列表。一步一步来。获得列表后,在网络上搜索如何在 Java 中对列表进行排序,您会发现海量示例,而且比创建问题并等待答案要快得多。
标签: java arrays sorting arraylist comparator