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语法。 请提供一些建议,以解决问题或改进方法。
答案 0 :(得分:3)
在br.readLine()
条件内删除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();
}
答案 1 :(得分: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()的返回值存储在变量行中,
,然后检查条件。因此,您无需在循环中再次调用它。