gpt4 book ai didi

java - 从 csv 文件打印特定行

转载 作者:行者123 更新时间:2023-12-01 13:39:52 24 4
gpt4 key购买 nike

我有一个 csv 文件,如下所示:

ID、价格、描述、长度、高度、类别

随后的每一列都填写了相关数据。我有一个读取器类,它读取此数据并将其显示在单独的演示类中(通过实例化它)。这是我读取 csv 文件的方式:

 public CatalogueReader(String filename) throws FileNotFoundException {
this.filename = filename;
this.catalogue = new Catalogue();

Scanner csvFile;
try {
csvFile = new Scanner(new File(filename));
} catch (FileNotFoundException fnf) {
throw new FileNotFoundException("File has not been found!!!! Probably in wrong place!");
}
csvFile.useDelimiter("\n");
boolean first = true;
String productCode;
double price;
String description;
double weight;
int rating;
String category;
boolean ageRestriction;
String rows;
while (csvFile.hasNextLine()) {
rows = csvFile.nextLine();
if (first) {
first = false;
continue;
}
System.out.println(rows);
String[] fields = rows.split(",");
productCode = (fields[0].trim());
price = Double.parseDouble(fields[1].trim());
description = fields[2].trim();
weight = Double.parseDouble(fields[3].trim());
rating = Integer.parseInt(fields[4].trim());
category = fields[5].trim();
ageRestriction = Boolean.parseBoolean(fields[6].trim());
catalogue.addAProduct(new Item(productCode, price, description, weight, rating, category, ageRestriction));
//System.out.println("PC is " + productCode);
}
csvFile.close();
}

我的问题是,有没有一种方法可以根据特定 ID 打印出特定行?

任何指导将不胜感激。

最佳答案

通过在方法中传递值,您可以逐行检查该值是否打破了循环。

public void CatalogueReader(String filename,String id) throws IOException{
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";

br = new BufferedReader(new FileReader(filename));
while ((line = br.readLine()) != null) {

// use comma as separator
String[] lineArray = line.split(cvsSplitBy);
//Check the value from array
//if(lineArray[xxx]==id){
//Print the line
break;
}



if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

关于java - 从 csv 文件打印特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20922553/

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