gpt4 book ai didi

java - 在 Java 中对 CSV 文件中的列进行排序

转载 作者:行者123 更新时间:2023-12-01 11:37:57 25 4
gpt4 key购买 nike

我有一个 CSV 文件,其中包含此内容。

City,Job,Salary
Delhi,Doctors,500
Delhi,Lawyers,400
Delhi,Plumbers,100
London,Doctors,800
London,Lawyers,700
London,Plumbers,300
Tokyo,Doctors,900
Tokyo,Lawyers,800
Tokyo,Plumbers,400
Lawyers,Doctors,300
Lawyers,Lawyers,400
Lawyers,Plumbers,500
Hong Kong,Doctors,1800
Hong Kong,Lawyers,1100
Hong Kong,Plumbers,1000
Moscow,Doctors,300
Moscow,Lawyers,200
Moscow,Plumbers,100
Berlin,Doctors,800
Berlin,Plumbers,900
Paris,Doctors,900
Paris,Lawyers,800
Paris,Plumbers,500
Paris,Dog catchers,400`

现在,我想对 Salary 列进行排序并将其写入 txt 文件。

我可以访问该列,但无法对其进行排序。我对 Java 的 CSV 阅读部分很陌生。有人可以帮忙吗!我应该如何将每个薪水值存储到变量中。

import java.io.*;

public class Main {

public static void main(String args[]) throws FileNotFoundException
{
String csv="C:\\Users\\Dipayan\\Desktop\\salaries.csv";
BufferedReader br= new BufferedReader(new FileReader(csv));
String line="";

try {
br.readLine();

while((line = br.readLine())!=null)
{
String[] f=line.split(",");
System.out.println(" Salary ="+f[2]);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

最佳答案

你可以尝试类似的方法 -

String csv="/home/user/Desktop/salaries.csv";
BufferedReader br= new BufferedReader(new FileReader(csv));
String line;
Map<Integer, String> salaryMap = new TreeMap<Integer, String>();

try {
br.readLine();
while((line = br.readLine()) != null) {
salaryMap.put(Integer.parseInt(line.split(",")[2]), line);
}
} catch (IOException e) {
e.printStackTrace();
}


try {
FileWriter fw = new FileWriter("/home/user/Desktop/salaries.txt");
BufferedWriter bw = new BufferedWriter(fw);
List<String> list = new ArrayList<String>(salaryMap.values());
for (String str : list) {
bw.write(str);
bw.newLine();
}

bw.flush();
bw.close();

} catch (IOException e) {
e.printStackTrace();
}

关于java - 在 Java 中对 CSV 文件中的列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29806734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com