gpt4 book ai didi

java - 读取和操作 CSV 文件

转载 作者:行者123 更新时间:2023-11-30 03:57:36 27 4
gpt4 key购买 nike

我想读取 CSV 文件,如下所示:

DATE=2014-03-08;ID=01;AVG=10

public void readInputStream(InputStream in) throws IOException {
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";

try {


br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
while ((line = br.readLine()) != null) {
String[] date= line.split(cvsSplitBy);
if (line.contains("DATE")){
System.out.println(date[0]);
}}
br.close();
} catch (IOException e) {
e.printStackTrace();
}

}

我想按日期和 ID 求平均值?任何帮助

最佳答案

import java.io.*;
import java.util.*;

public class CsvSum{

static Map<String, Integer> map = new HashMap<String, Integer>();

public static void main(String args[]) throws Exception{
File file = new File("test.csv");
Scanner scanner = new Scanner(file);
while(scanner.hasNext()){
String line = scanner.next();
String[] columns = line.split(";");

String date = columns[0].replace("DATE=","");
String id = columns[1].replace("ID=","");
int avg = Integer.parseInt(columns[2].replace("AVG=",""));

String key = date + "_" +id;
if(!map.containsKey(key)){
map.put(key,avg);
}else{
Integer existing = map.get(key);
map.put(key, existing + avg);
}
}

System.out.println(map);
}
}

关于java - 读取和操作 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22757029/

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