Reading CSV file using BufferedReader resulting in reading alternative lines

前端 未结 3 1147
余生分开走
余生分开走 2020-12-21 12:26

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

public void readFile() throws IOException {
    BufferedReader         


        
相关标签:
3条回答
  • 2020-12-21 12:50

    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

    0 讨论(0)
  • 2020-12-21 12:51

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

    0 讨论(0)
  • 2020-12-21 12:55

    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.

    0 讨论(0)
提交回复
热议问题