-1

I want my code to read a txt file and print out each line, but nearly half of the lines are being skipped over seeming randomly. How do I ensure the entire file is read?

        BufferedInputStream readIt = new BufferedInputStream(new FileInputStream(pBase));
        //pBase is txt File object
        Scanner actualRead = new Scanner(readIt);

    
        while(actualRead.hasNextLine()){
            System.out.println("Line is : " + actualRead.nextLine());
            
        }
Matthias Berndt
  • 4,387
  • 1
  • 11
  • 25
6haune
  • 1

2 Answers2

0

The simplest way is to use one of the nio utility methods, such as readAllLines.

For large files that you don't want to load into memory all at once, you can use the lines method like so:

import java.nio.file.Files;
import java.nio.file.Path;
...
try (var lines = Files.lines(Paths.get(pBase))) {
  lines.forEach(l -> {
    System.out.println(l);
  });
}
Matthias Berndt
  • 4,387
  • 1
  • 11
  • 25
0

Alternatively..scanner can take a file parameter as input...


Scanner actualRead = new Scanner(pBase); //directly pass the file as argument...
//Although this threatens to throw an IOException..catch  it in try-catch or add to throws...
try {
  Scanner actualRead = new Scanner(pBase);
  while (actualRead.hasNextLine()) {
    System.out.println("Line is : " + actualRead.nextLine());
}
catch (IOException e) {
  System.out.println("err...");
    
Matthias Berndt
  • 4,387
  • 1
  • 11
  • 25
Jore
  • 322
  • 2
  • 8