【问题标题】:How to sort a csv file by a specific column in Java如何按Java中的特定列对csv文件进行排序
【发布时间】:2020-05-22 22:42:39
【问题描述】:

我需要按第三列对 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

【问题讨论】:

标签: java csv sorting


【解决方案1】:

这是一个使用带有 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());

【讨论】:

  • 请确保您的 CSV 值在某些引号内不包含 ,
猜你喜欢
  • 1970-01-01
  • 2017-11-28
  • 2015-12-24
  • 2021-09-04
  • 2015-10-29
  • 2016-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多