Salman Raza
Salman Raza

Reputation: 1715

How to read a file from end to the beginning?

How to read file from end to the beginning my code,

  try                
   {
      String strpath="/var/date.log";
      FileReader fr = new FileReader(strpath);
      BufferedReader br = new BufferedReader(fr);
      String ch;
      String[] Arr;
      do 
      {
        ch = br.readLine();
        if (ch != null)
        out.print(ch+"<br/>");   
      } 
      while (ch != null);
      fr.close();
    }
    catch(IOException e){
    out.print(e.getMessage());
  }

Upvotes: 0

Views: 5458

Answers (3)

Yegoshin Maxim
Yegoshin Maxim

Reputation: 881

If you don't want to use temporary data(for reversing the file) you should use RandomAccessFile class.

In other case you can read and store the whole file in memory, then reversing it contents.

List<String> data = new LinkedList<String>();

If you need lines in reverse order, insted of:

out.print(ch+"<br/>");

do

data.add(ch);

And after reading the whole file you can use

Collections.reverse(data);

If you need every symbol to be in reverse order, you can use type Character instead of String and read not the whole line but only one symbol. After that simply reverse your data.

P.S. To print (to system output stream for example) you should iterate over each item in collection.

for (String line : data) {
   out.println(line);
}

If you use just out.print(data) this will call data.toString() method and print out its result. Standart implementation of toString() will not work as you expected. It will return something like object type and number.

Upvotes: 1

Mikita Belahlazau
Mikita Belahlazau

Reputation: 15434

If you need print lines in reverse order:

  1. Read all lines to list
  2. Reverse them
  3. Write them back

Code:

List<String> lines = new ArrayList<String>();
String curLine;
while ( (curLine= br.readLine()) != null) {
  lines.add(curLine);
}
Collections.reverse(lines);
for (String line : lines) {
  System.out.println(line);
}

Upvotes: 2

Sergey Grinev
Sergey Grinev

Reputation: 34508

You can use RandomAccessFile class. Either just read in loop from file length to 0, or use some convenience 3rd party wraps like http://mattfleming.com/node/11

Upvotes: 3

Related Questions