Reading CSV file using BufferedReader resulting in reading alternative lines

落爺英雄遲暮 提交于 2020-11-25 03:31:25

问题


I'm trying to read a csv file from my java code. using the following piece of code:

public void readFile() throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    lines = new ArrayList<String>();
    String newLine;
    while ((newLine = br.readLine()) != null) {
        newLine = br.readLine();
        System.out.println(newLine);
        lines.add(newLine);
    }
    br.close();
}

The output I get from the above piece of code is every alternative line [2nd, 4th, 6th lines] is read and returned by the readLine() method. I'm not sure why this behavior exists. Please correct me if I am missing something while reading the csv file.


回答1:


The first time you're reading the line without processing it in the while loop, then you're reading it again but this time you're processing it. readLine() method reads a line and displaces the reader-pointer to the next line in the file. Hence, every time you use this method, the pointer will be incremented by one pointing to the next line.

This:

 while ((newLine = br.readLine()) != null) {
        newLine = br.readLine();
        System.out.println(newLine);
        lines.add(newLine);
    }

Should be changed to this:

 while ((newLine = br.readLine()) != null) {
        System.out.println(newLine);
        lines.add(newLine);
    }

Hence reading a line and processing it, without reading another line and then processing.




回答2:


You need to remove the first line in a loop body newLine = br.readLine();




回答3:


In java 8, we can easily achieve it

InputStream is = new ByteArrayInputStream(byteArr);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
List<List<String>> dataList = br.lines()
           .map(k -> Arrays.asList(k.split(",")))
           .collect(Collectors.toCollection(LinkedList::new));

outer list will have rows and inner list will have corresponding column values



来源:https://stackoverflow.com/questions/11990211/reading-csv-file-using-bufferedreader-resulting-in-reading-alternative-lines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!