繁体   English   中英

如何按 Java 中的特定列对 csv 文件进行排序

[英]How to sort a csv file by a specific column in Java

我需要按第三列对 csv 文件进行排序,但我被卡住了,找不到解决方案。

代码:

import java.util.*;
import java.io.*;
public class SalesStatistics{
public static void main(String[] args){

String filePath = "Filepath";

ArrayList<String> csvValues = new ArrayList<String>();
try{

BufferedReader br = new BufferedReader( new FileReader(filePath));
String strLine = "";
StringTokenizer str = null;

while( (strLine = br.readLine()) != null){
str = new StringTokenizer(strLine, ",");

while(str.hasMoreTokens())
csvValues.add(str.nextToken());
}

}catch(Exception e){
System.out.println("Exception while reading csv file: " + e);
}
}
}

我的 csv 文件是这样的:

1001,Name1,9
1005,Name2,20
1007,Name3,14

我需要它是:

1001,Name1,9
1007,Name3,14
1005,Name2,20

这是使用具有 lambda 语法的流的 Java 8 解决方案。

String filePath = "Filepath";
String content = Files.lines(Path.of(filePath))
                      .sorted(Comparator.comparing(line -> Integer.parseInt(line.split(",")[2])))
                      .collect(Collectors.joining("\n"));
Files.write(Paths.get("OutputFilepath"), content.getBytes());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM