Reversing the lines of a file I am trying to reverse the lines of a file by reading the file through an array.

Is there a more efficient and quicker way of achieving this?

import java.util.Scanner;
import java.io.*;

class ReverseNumbers {

    public static void main(String[] args) throws FileNotFoundException {

        File file = new File("numbers.txt");
        Scanner Scan = new Scanner(file);

        int numoflines = 0;
        while(Scan.hasNextLine()) {
            Scan.nextLine();
            numoflines++;
        }
        Scan.close();
        Scan = new Scanner(file);

        int buffer[] = new int[numoflines]; //size

        for(int i=0; i&lt;buffer.length; i++) {
            buffer[i] = Scan.nextInt();
        }

        for(int i=buffer.length-1; i&gt;=0; i--) {
            int reverse = buffer[i];
            System.out.println(reverse);
        }
    }
}
The posted code does the following:


Read all lines, just for counting
Create an array with the right size
Read all lines again, this time for storing
Print all lines in reverse order


It's wasteful to read a file completely just to find the number of lines, and then need to read the file again to store the content.
It would be better to store the lines in a data structure that can grow its capacity as needed, to eliminate the need to know the number of lines in advance. That is, use any List implementation.

Possible bug

The description doesn't mention that there is precisely one integer per line in the input.
It must be the case, otherwise this code may not work well:


for(int i=0; i&lt;buffer.length; i++) {
    buffer[i] = Scan.nextInt();
}



That is, if there are multiple numbers per line, then you will not read the entire file,
only the first \$N\$ numbers.
Similarly, if there are empty lines, then there may not be enough numbers,
and then the .nextInt call will throw a NoSuchElementException.

The thing is, since there program doesn't use any integer operation,
only read and print,
there's no point reading integers.
Keep in mind that when you read integers,
you also incur a parsing step.
It would make more sense to read the lines as strings,
it would be simpler, and it seems that's all you really need anyway.

Suggested implementation

Here's an alternative, more efficient solution,
that also simplifies the reversing logic using a LinkedList, with a descendingIterator:

LinkedList&lt;String&gt; lines = new LinkedList&lt;&gt;();
while (scanner.hasNextLine()) {
    lines.add(scanner.nextLine());
}
scanner.close();

Iterator&lt;String&gt; iterator = lines.descendingIterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}