【问题标题】:skipping lines while reading from csv file in java [duplicate]从java中的csv文件读取时跳过行[重复]
【发布时间】:2019-12-02 11:50:06
【问题描述】:
private static List<Book> readDataFromCSV(String fileName) {    
    List<Book> books = new ArrayList<>();
    Path pathToFile = Paths.get(fileName);

    // create an instance of BufferedReader
    // using try with resource, Java 7 feature to close resources
    try (BufferedReader br = Files.newBufferedReader(pathToFile,
            StandardCharsets.US_ASCII)) {
        // read the first line from the text file
        String line = br.readLine();

        // loop until all lines are read
        while ((line  = br.readLine())!= null) {
            // use string.split to load a string array with the values from
            // each line of
            // the file, using a comma as the delimiter
            String[] attributes = line.split("\\|");

            Book book = createBook(attributes);

            // adding book into ArrayList
            books.add(book);

            // read next line before looping
            // if end of file reached, line would be null
            line = br.readLine();
        }

    } catch (IOException ioe) {
        ioe.printStackTrace();
    } 
    return books;
}


private static Book createBook(String[] metadata) { 
    String name = metadata[0];  
    String author = metadata[1]; // create and return book of this metadata 
    return new Book(name, price, author); 
} 

上面的代码从文本文件(一个 csv 文件)中跳过每一行。 它提供交替行的数据,并使用 Java 7 语法。 请提供一些建议是什么错误或如何改进它。

【问题讨论】:

标签: java string csv


【解决方案1】:

删除while条件内的br.readLine(),即

// read the first line from the text file
String line = br.readLine();
// loop until all lines are read
while (line != null)
{
    ...
    // read next line before looping
    // if end of file reached, line would be null
    line = br.readLine();
}

【讨论】:

  • 因为他想读每 2 行中的 1 行,所以我认为这行不通。
  • @LocTruong 据我了解,这是实际问题,OP 想要阅读每一行。
  • 是的,它有效。但是当我执行 SOP(name) 时,它会从文件中间开始打印。
【解决方案2】:

您在循环中调用了 br.readLine() 函数两次。

一个处于条件:

while((line = br.readLine()) != null)

第二个在循环的末尾。

所以循环实际上是在末尾读取一行,然后在开头读取下一行而不处理它。为避免这种情况,您可以在循环结束时删除 br.readLine。

while ((line  = br.readLine())!= null)
                {

                    // use string.split to load a string array with the values from
                    // each line of
                    // the file, using a comma as the delimiter
                   String[] attributes = line.split("\\|");

                   Book book = createBook(attributes);

                   // adding book into ArrayList
                   books.add(book);
               }

如果没有得到,条件:

while((line = br.readLine()) != null)

实际上是在做以下事情:

将 br.readLine() 的返回值存储在变量 line 中,

然后检查条件。因此,您无需在循环中再次调用它。

【讨论】:

    猜你喜欢
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多