gpt4 book ai didi

java - 在java中读取csv文件时跳行

转载 作者:行者123 更新时间:2023-12-01 16:43:04 25 4
gpt4 key购买 nike

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 语法。请提供一些建议,什么是错误的或如何改进。

最佳答案

删除 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();
}

关于java - 在java中读取csv文件时跳行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59138365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com