I have the following method to read a file and output its lines in reverse order:
public void Reverse(BufferedReader br, PrintWriter pw)
{
try
{
String headLine = br.readLine();
if (headLine != null)
{
Reverse(br, pw);
pw.println(br.readLine());
}//if
pw.println(headLine);
}//try
}//Reverse
For some reason, I am not seeing anything in the output file when the code is run It is compiling correctly though. Any ideas?
Firstly, your code won’t even compile – you have a try block with no catch or finally block. When we can’t see your real code, it’s even harder than normal to know for sure what’s going on.
Secondly, you’re calling
readLine()twice for no obvious reason, and then writing outheadLineeven if it’s null. Shouldn’t your code really be:without the extra
printlnafterwards?My guess is that you’re never flushing or closing the
PrintWriter, and you’ve got auto-flush turned off. Don’t do that. Or maybe there’s an exception somewhere, whichPrintWriterisn’t going to report because it swallows them. Personally I’d recommend taking just aWriterorBufferedWriterinstead of aPrintWriter, and declaring thatReversecan throwIOException. Then make sure that the calling code closes the writer in a finally block.I’d also suggest not using recursion for this, unless you’re just using this as a way of investigating recursion. It would be far saner to read the whole file into a list of strings, reverse it, then write it all out.