0

Here is my code - I am trying to reverse the contents of a file by reading the file through an array.

Is there a more efficient and quicker way of achieving this? I feel this is too much for this type of question?

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<buffer.length; i++) {
            buffer[i] = Scan.nextInt();
        }

        for(int i=buffer.length-1; i>=0; i--) {
            int reverse = buffer[i];
            System.out.println(reverse);
        }
    }
}
  • 3
    I'm voting to close this question as off-topic because code that works but you wish to improve may better belong on [Code Review](http://codereview.stackexchange.com/). Make sure to read that sites list of on-topic questions first! – Shepmaster Feb 19 '15 at 18:52
  • I agree with @Shepmaster. Just as an idea though, you could read the file line at a time and add each line to the head of a List (LinkedList or ArrayList). This would probably be a decently efficient solution. – But I'm Not A Wrapper Class Feb 19 '15 at 19:51

1 Answers1

0
import java.io.*;
import java.util.*;
class FileReaderReverse
{
    public static void main(String[] args) throws IOException,FileNotFoundException  
    {   
       FileReader fr=new FileReader("abcd.txt");  
       BufferedReader br=new BufferedReader(fr);  
       String s;  

       List<String> tmpr = new ArrayList<String>(); 
       do 
       {   
           s = br.readLine();  
           tmpr.add(s);  
       }while(s!=null);  


       for(int i=tmpr.size()-1;i>=0;i--) {

           System.out.println(tmpr.get(i));  
       }   
    }
}

Try this code it's fast.