从java中的csv文件读取时跳过行 [英] skipping lines while reading from csv file in java
本文介绍了从java中的csv文件读取时跳过行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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语法.请提供一些建议或建议,以解决问题.
The above code skips every second line from text file (a csv file). It gives data of alternate lines and it uses Java 7 syntax. Please provide some suggestion what is wrong or how to improve it.
推荐答案
在 while
条件(即
// 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中的csv文件读取时跳过行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文