我正在尝试编写一个简单地读取 CSV 文件并存储文件中数据的方法。这是我尝试读取的 CSV 文件的屏幕截图的链接,以及此方法的代码:
public static void correctPrices(String correctfile) {
String data;
Date date;
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
File correctedfile = new File(correctfile);
Scanner correct;
try {
correct = new Scanner(correctedfile);
correct.nextLine(); //to avoid reading the heading
ArrayList<Date> correctdate = new ArrayList<Date>();
ArrayList<String> correctdata = new ArrayList<String>();
while (correct.hasNext()) {
correctdata.add(correct.nextLine());
//data = correct.nextLine();
//String[] corrected = correct.nextLine().split(",");
//date = formatter.parse(corrected[0]);
//correctdate.add(date);
}
for (int i = 0; i < correctdata.size(); i++) {
System.out.println(correctdata.get(i));
}
}
catch (FileNotFoundException ex) {
Logger.getLogger(DataHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
正如预期的那样,此代码将输出文件的最后 2 行。但是,当我取消注释 data = correct.nextLine(); 在 while 循环中,输出将只返回 CSV 的第二行,而不是最后一行。我对此有点困惑?我所做的只是将该行存储到另一个变量中,为什么要省略最后一行?感谢您的帮助和时间,如果您需要任何其他信息,请告诉我!