0

I am just trying to reverse the lines which I receive from the input, but every single time I run my code, the output.txt file is empty. What am I missing? It appears mostly correct to me, even the recursion passage.

Thanks

import java.io.BufferedReader; 
import java.io.FileReader;
import java.io.FileWriter; 
import java.io.PrintWriter;

public class ReverseLines { 

  public static BufferedReader input;
  public static PrintWriter output;

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

    input = new BufferedReader(new FileReader(args[0]));
    output = new PrintWriter(new FileWriter(args[1]));
    reverse(input, output);

  }

  public static void reverse( BufferedReader input, PrintWriter output)
         throws Exception { 

    String line = input.readLine();
    if(line != null) {
    reverse (input, output);
    output.println(line);
    }    

  }

}
Edoardo Moreni
  • 408
  • 2
  • 10
  • 24

2 Answers2

3

Close the PrintWriter in your main method:

output.close();
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • 1
    Make sure you close it in the `main` method, not in the recursive `reverse` method. – Rob Watts Apr 09 '13 at 18:32
  • A bit more explanation: The important thing here is, `output.close()` flushes buffers, in other words writes everything to disk. It would be possible to do just `output.flush()`, which is would sort of fix the problem of empty output file. Of course files must still be closed, and unnecessary flushing can hurt performance and clutters the code, so nothing wrong with this answer. – hyde Apr 09 '13 at 18:36
0

do output.flush() and check whether it works!

Kijewski
  • 25,517
  • 12
  • 101
  • 143
Nomesh Gajare
  • 855
  • 2
  • 12
  • 28