【问题标题】:Issue during reading a CSV file has me stumped读取 CSV 文件时的问题让我很困惑
【发布时间】:2012-07-02 19:48:11
【问题描述】:

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

【问题讨论】:

    标签: java csv java.util.scanner


    【解决方案1】:

    问题是,当您调用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);
    }
    

    【讨论】:

    • 成功了!谢谢你。一旦我现在看它就说得通了,但我想我将正确的.nextLine() 本身视为一个变量,并没有考虑指针递增。
    • 是的,一个常见的错误。有状态编程的众多乐趣之一。
    猜你喜欢
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多