我有一个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打印特定行的方法?
非常感谢任何指导。
答案 0 :(得分:0)
您可以通过row.contains(searchID)进行检查。您只能在searchID匹配时进行解析。我刚刚添加 if(!rows.contains(productCode))继续; 进行此检查
while (csvFile.hasNextLine()) {
rows = csvFile.nextLine();
if (first) {
first = false;
continue;
}
if(!rows.contains(productCode)) 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);
}
答案 1 :(得分:0)
通过传递方法中的值,您可以逐行检查该值,如果该行已找到中断循环。
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();
}
}
}