954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Need Recursion and File I/O Java Help!

import java.io.*;public class Ex9a{

public void rollBack(BufferedReader in) throws IOException{	
	String line=""; 
	if((line=in.readLine())!=null){	 
		rollBack(in);	 
		}	 
	if(line!=null&&!"".equals(line)){ System.out.println(line);	 
	}	
}	 
	public static void main(String[] args) throws FileNotFoundException{	
		PrintStream out;
		
		Ex9a t=new Ex9a();		 
		out = new PrintStream(new FileOutputStream("outfile.txt"));
		out.println(ioe);
		out.close( );

		String fileName="infile.txt";	 
		try{	 
			BufferedReader in=new BufferedReader(new FileReader(fileName));
			t.rollBack(in);	 
			}catch(IOException ioe){
				System.out.println(ioe);	
				}	
			}
	}


infile is basically a bunch of lines of a poem and I need to reverse these lines and output them into an out file. The output file is created but it has nothing in it. Please help.

jishent
Newbie Poster
1 post since Nov 2010
Reputation Points: 10
Solved Threads: 0
 

Read each line and put it in a stack. Once that is done, remove each element from the stack and print it out.

cale.macdonald
Junior Poster
153 posts since Jun 2009
Reputation Points: 16
Solved Threads: 31
 

You're not actually writing anything to the file, which is why it comes back empty.

out = new PrintStream(new FileOutputStream("outfile.txt"));
		out.println(ioe);
		out.close( );


I'm not sure how this compiles, since there is nothing called ioe in scope at this point. This just creates outfile.txt for writing and closes it.


Your recursive read looks good. What if you passed it the handle to the outfile ("out" in your code) and replace the print-to-screen with a write-to file?
You'll want to delay the out.close() call until after the rollback method terminates.

jon.kiparsky
Posting Virtuoso
1,849 posts since Jun 2010
Reputation Points: 383
Solved Threads: 187
 

Cale - that's a correct solution, for a different problem.

jon.kiparsky
Posting Virtuoso
1,849 posts since Jun 2010
Reputation Points: 383
Solved Threads: 187
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: