Home > Blockchain >  How to create method with same functionality as Scanner.hasNext() do but using BufferedReader
How to create method with same functionality as Scanner.hasNext() do but using BufferedReader

Time:11-06

Need a method that jsut verify if the next line in the file is not null. But i dont know how to make it without go to the next line BufferedReader.readLine() so reader goes through line;

I need SEPARETE method getNext()

i need smth like this.

var reader = new BufferedReader(new FileReader("src/main/resources/math.txt"));

public String func(){
    if(reader.hasNext){
    return reader.nextLine();
    }
}

CodePudding user response:

You mean something like this?

BufferedReader br = new BufferedReader (new FileReader ("src/main/resources/math.txt"));
String line;

while( (line = br.readLine() ) != null) {
    System.out.printf(line);
}

CodePudding user response:

We can also try the following to return all the lines in one go as a list.

List<String> lines = Collections.emptyList();

try(Reader reader = new FileReader("<file path>")) {    
    lines.addAll(IOUtils.readLines(new BufferedReader(new FileReader("<file path>"))));
} catch (Exception ex) {
  // throw the stacktrace or log error
}
  •  Tags:  
  • java
  • Related