Results 1 to 7 of 7
  1. #1
    viperlasson is offline Member
    Join Date
    Jan 2010
    Posts
    16
    Rep Power
    0

    Default Open/Read file using recursion

    Hello, I am having a tough time trying to change my code from reading a text file using a while loop, to reading a file using recursion...

    This is my little test program now. It opens up input.txt and reads the input using a while loop and stringtokenizer.

    Java Code:
    import java.io.*;
    import java.util.*;
    
    
    class test
    {
    	public static void main (String[] args) throws java.io.IOException
    	 {
    
    		 String filename = "input.txt";
    		 
    		 // Initialize the reader
    		 BufferedReader reader = null;
    		 try {
    		 reader = new BufferedReader(new FileReader(filename));
    		 } catch (FileNotFoundException e) {
    		 e.printStackTrace();
    		 }
    		 
    		 // Initialize the string variable that will contain each
    		 // line of text read from the file
    		 String s = "";
    		 // Read until the end of file
    		 while (s!=null) 
    			 {
    			 try {
    			 s = reader.readLine();
    			 } catch (IOException e) {
    			 e.printStackTrace();
    			 }
    			    if (s != null)
    			    {
    		
    				    StringTokenizer st = new StringTokenizer (s);
    				    String test;
    
    				     while (st.hasMoreTokens()) 
    				     {
    				    	 
    
    				    	 test = st.nextToken();
    				    	 if (test.equalsIgnoreCase("q"))
    				         {
    				        	 System.out.println ("User quit.");
    				        	 break;
    				         }
    				         if (test.equalsIgnoreCase("one"))
    				        	 System.out.println ("1");
    				         if (test.equalsIgnoreCase("two"))
    				        	 System.out.println ("2");
    				         if (test.equalsIgnoreCase("three"))
    				        	 System.out.println ("3");
    				     }
    
    			    } //end if
    			    
    			    
    			 } //end while
    		
    	 } //end main
    } //end class
    the input.txt contains

    Java Code:
    one
    two
    three
    q
    and works fine as far as I can tell. So now when making a recursive method to do this... I'll need to call the nextToken() recursively with hasMoreTokens() being the base case? Recursive code is always confusing to me...

    Thanks for your time.

  2. #2
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    952
    Rep Power
    5

    Default

    I'm having trouble imagining why you would want to read the file recursively -- I assume it must be a course assignment.

    I think you'll find that !reader.ready() will actually be your base case -- that is the condition that will tell you that you are done recursing and can return without doing anything more. Then I guess you want to read and process a line, then recurse (call another copy of your method) to do the rest of the file. It doesn't seem like anything I'd do in practice. I suppose you could make it print the file in reverse order, which would at least be doing something.

    -Gary-

  3. #3
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default

    I think that simple form of recursion for your program is:

    Java Code:
    		void myRecursion(String s) {
    			if(s == null)
    				return;
    			else {
    					String newString = reader.readLine();
    					myRecursion(newString);
    					return;
    			}
    		}
    populate rest of your program using copy-paste code from your program into the right place, and maybe change few things.

  4. #4
    viperlasson is offline Member
    Join Date
    Jan 2010
    Posts
    16
    Rep Power
    0

    Default

    Okay I am still having trouble trying to read a file recursively. I simplified my test program to just try to print out each token per line, but I'm getting an infinite loop after the first token is printed...

    Here's what I have

    Java Code:
    import java.io.*;
    import java.util.*;
    
    
    class test
    {
    	public static void main (String[] args) throws java.io.IOException
    	 {
    
    		String meh = "";
    		 myRecursion(meh);
    		
    	 } //end main
    	
    	//using recursion to read a file
    	static void myRecursion(String s) {
    		
    		
    		String filename = "input.txt";
    		 
    		 // Initialize the reader
    		 BufferedReader reader = null;
    		 try {
    		reader = new BufferedReader(new FileReader(filename));
    		 } catch (FileNotFoundException e) {
    		 e.printStackTrace();
    		 }
    			 try {
    			 s = reader.readLine();
    			 } catch (IOException e) {
    			 e.printStackTrace();
    			 }
    		StringTokenizer st = new StringTokenizer (s);
    				   
    		System.out.println (st.nextToken());
    		
    		
    		
    		if(s == null)
    			return;
    		else {
    				myRecursion(s);
    				return;
    			}
    	} //end method
    } //end class
    Shouldn't it be going to the next token when myRecursion is called again?

  5. #5
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default

    Java Code:
    static void myRecursion(String s) {
    		
    		
    		String filename = "input.txt";
    		 
    		 // Initialize the reader
    		 BufferedReader reader = null;
    		 try {
    		reader = new BufferedReader(new FileReader(filename));
    		 } catch (FileNotFoundException e) {
    		 e.printStackTrace();
    		 }
    			 try {
    			 s = reader.readLine();
    			 } catch (IOException e) {
    			 e.printStackTrace();
    			 }
    		StringTokenizer st = new StringTokenizer (s);
    				   
    		System.out.println (st.nextToken());
    So, every time when function call itself you have this:
    my filename = input.txt
    buffreader = null
    then let's see if file input.txt is missing or not
    then let's read first line from file
    then let's print that.
    Then fuction call itself again and what we have?
    my filename = input.txt
    buffreader = null
    then let's see if file input.txt is missing or not
    then let's read first line from file
    then let's print that.
    ....
    and that's infinite loop.

  6. #6
    StormyWaters is offline Senior Member
    Join Date
    Feb 2009
    Posts
    307
    Rep Power
    6

    Default

    Why don't you try adding the BufferedReader as a parameter to the recursion method. Don't make opening the file part of the recursion method as this will make you start off at the beginning every time.

  7. #7
    viperlasson is offline Member
    Join Date
    Jan 2010
    Posts
    16
    Rep Power
    0

    Default

    Alright! I think it is working correctly now! Thanks a lot for everyone's help, I really appreciate it :)

    Here is my final code, if anyone else needs help or wants to look what I did

    Java Code:
    import java.io.*;
    
    class test
    {
            //main method
    	public static void main (String[] args) throws java.io.IOException
    	 {
    		String filename = "input.txt";
    		 
    		 // Initialize the reader
    		 BufferedReader reader = null;
    		 try {
    			 reader = new BufferedReader(new FileReader(filename));
    		 } 
    		 catch (FileNotFoundException e) {
    			 e.printStackTrace();
    		 }
    		 
    		//recursive call
    		myRecursion(reader);
    		
    	 } //end main
    	
    	//method using recursion to read a file
    	static void myRecursion(BufferedReader br) 
    	{
    		String s1 = "";
    		
    		try {
    			 s1 = br.readLine();
    		 }
    		 catch (IOException e) {
    			 e.printStackTrace();
    		 }
    
    		if(s1 == null)
    			return;
    		else 
    		{
    			System.out.println (s1);
    			myRecursion(br);
    			return;
    		}
    	} //end method
    } //end class
    putting an instance of BufferedReader in the method did the trick.

Similar Threads

  1. writing results of recursion into file
    By sara12345 in forum New To Java
    Replies: 2
    Last Post: 04-12-2010, 02:22 PM
  2. Read and Open *.txt Files? help!!
    By ashton in forum New To Java
    Replies: 9
    Last Post: 11-01-2009, 04:42 PM
  3. open a file using read or write mode
    By swati.jyoti in forum New To Java
    Replies: 2
    Last Post: 04-25-2009, 05:44 PM
  4. Different Files Open in File -> Open Workspace
    By mgm2010 in forum JCreator
    Replies: 0
    Last Post: 04-11-2009, 03:14 PM
  5. Open xls file in read-write mode
    By rdhaware in forum Advanced Java
    Replies: 1
    Last Post: 02-03-2009, 09:12 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •