2

我正在尝试编写一个简单地读取 CSV 文件并存储文件中数据的方法。这是我尝试读取的 CSV 文件的屏幕截图的链接,以及此方法的代码:

http://i.imgur.com/jsGTg.png

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 的第二行,而不是最后一行。我对此有点困惑?我所做的只是将该行存储到另一个变量中,为什么要省略最后一行?感谢您的帮助和时间,如果您需要任何其他信息,请告诉我!

4

1 回答 1

2

问题是,当您调用 时correct.nextLine(),它会读取一行,然后将文件中的指针递增到您正在读取的位置。由于您在循环中多次调用它,它会多次增加指针,跳过行。您应该做的只是在 while 循环开始时使用

data = correct.nextLine();

然后用 . 替换correct.nextLine()它出现在循环中的其他任何地方data

换句话说,你的while循环看起来像

while (correct.hasNext())
{
    data = correct.nextLine();
    correctdata.add(data);
    String[] corrected = data.split(",");
    date = formatter.parse(corrected[0]);
    correctdate.add(date);
}
于 2012-07-02T19:55:22.190 回答