简体   繁体   中英

BufferedReader.readLine() returning all lines as null

I have some very simple code to ready content of txt file, line by line and put it into String[], however buffered reader return all lines as "null" - any idea on what might be the reason? *I want to use buffered reader and not other options as this is just part of java training excersise and mostly I want to understand where is the mistake i made. thanks!

public static void readFile (String path){
    File file = new File(path);
    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        int lineCount = (int) br.lines().count();
        String[] passwords = new String[lineCount];

        for (int i=0; i<lineCount; i++){
            passwords[i] = br.readLine();;
            System.out.println(passwords[i]);
        }
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

}

By using the lines() method you basically move the buffered reader position to the end of the file. It's like you already read these lines.

Try using this in order to iterate through all lines:

while ((line = br.readLine()) != null) {  
  // Use the line variable here  
}

Use br.lines() or br.readLine() to consume the input, but not both at the same time. This version does the same using just the stream to String[], and closes the inputs in try with resources block:

public static String[] readFile(Path path) throws IOException {
    try (BufferedReader br = Files.newBufferedReader(path);
        Stream<String> stream = br.lines()) {
        return stream.peek(System.out::println)
                          .collect(Collectors.toList())
                          .toArray(String[]::new);
    }
}

String[] values = readFile(Path.of("somefile.txt"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM