-1

I have a simple function to read a file, however it only reads lines, and I would like it before reading the contents of each lines, I already had the total value of rows in the file.

    try {
        FileReader leitor = new FileReader("config.txt");
        //file to reade

        BufferedReader buffer = new BufferedReader(leitor, 2 * 1024 * 1024);
        String linha = buffer.readLine();
        while (linha != null) {
            //I want to do an "if" here to get the value of the last line of the file and save in a variable.


            System.out.print(linha + "\n");
            linha = buffer.readLine();
            Thread.sleep(1000);
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (
            IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InterruptedException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

Thanks.

Sabrina B.
  • 306
  • 1
  • 8
  • 23
  • 2
    Possible duplicate of [Number of lines in a file in Java](https://stackoverflow.com/questions/453018/number-of-lines-in-a-file-in-java) – Samuel Philipp Apr 27 '19 at 23:23
  • 1
    You would like this why? You can only get it by reading the file twice,a and that should never be necessary. – user207421 Apr 28 '19 at 02:07

1 Answers1

0

When I implemented the long count = buffer.lines().Count(); I got the number of lines of the file, but after counting it prevented from moving on to the next line, since the line = buffer.readLine(); not working anymore.

Then I found the solution below

//get the path of file
Path path = Paths.get("./config.txt");
//count the lines number
int linesNumber = ((int) Files.lines(path).count());
Sabrina B.
  • 306
  • 1
  • 8
  • 23