Results 1 to 15 of 15
  1. #1
    bigsonny is offline Senior Member
    Join Date
    Nov 2010
    Posts
    164
    Rep Power
    4

    Default Trying to read a file, then writing the info into another file

    Hello JF residents,

    I have a new problem, still going through the Java tutorial over at the Oracle site. I am excited because I went through the generic tutorial and while I get it conceptually, I am not yet comfortable using it. Same can be said of the Exceptions tutorial. Asides from throws IOException which I mostly use because I saw it everywhere, it is not yet instinctive, but I'm working on that.

    So what I am excited about? Well, I have arrived to the Essential classes, specifically going through "Basic I/O" which is the class that I had been looking to learn the most from.

    So here is the problemo. I just went through the Scanning lesson plan which has a very nice little class called ScanXan which read from a file and prints it back to the screen. So I tried it, understood everything and thought...yay. So then I thought this is good and all, but let's print this output to a file and not just the screen, so Modified to the code to the following:

    Java Code:
    import java.io.*;
    import java.util.Scanner;
    
    
    public class ScanXan2 {
        public static void main(String[] args) throws IOException {
            Scanner s = null;
    		  PrintWriter output = null;
    		  
    		  
            try {
                s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
    				output = new PrintWriter (new FileWriter ("xanaduout.txt"));
    				
                while (s.hasNext()) {
                    System.out.println(s.next());
    					 output.println(s.next());
    					 
                }
            } finally {
                if (s != null) {
                    s.close();
                }
            }
        }
    }
    The outputs are:
    1) It prints each token to the screen, one token per line.
    2) It creates my file "xanaduout.txt"
    3) It DOES NOT print the token to the screen.

    So then I went back and re-read the Scanner class. It says that it is "A simple text scanner which can parse primitive types and strings using regular expressions" so I thought, well, maybe I need a string, so I assigned the readout to a String type which I then try to print to the file:

    Java Code:
    import java.io.*;
    import java.util.Scanner;
    
    
    public class ScanXan2 {
        public static void main(String[] args) throws IOException {
            Scanner s = null;
    		  PrintWriter output = null;
    		  
    		  
            try {
                s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
    				output = new PrintWriter (new FileWriter ("xanaduout.txt"));
    				
                while (s.hasNext()) {
                    System.out.println(s.next());
    					 String l = s.next();
    					 output.println(l);
    					 
                }
            } finally {
                if (s != null) {
                    s.close();
                }
            }
        }
    }
    Outcome? same as before, no text in my file. I am wondering if you would be able to point me in the right direction. What am I not understanding about these classes?

    thanks!

  2. #2
    Dark's Avatar
    Dark is offline Senior Member
    Join Date
    Apr 2011
    Location
    Camp Lejuene, North Carolina
    Posts
    643
    Rep Power
    4

    Default

    Why don't you just use the FileReader/FileWriter instead of ScanXan?
    • Use [code][/code] tags when posting code. That way people don't want to stab their eyes out when trying to help you.
    • +Rep people for helpful posts.

  3. #3
    bigsonny is offline Senior Member
    Join Date
    Nov 2010
    Posts
    164
    Rep Power
    4

    Default

    because I'm new and I'm still trying to get a hold of this.

  4. #4
    bigsonny is offline Senior Member
    Join Date
    Nov 2010
    Posts
    164
    Rep Power
    4

    Default

    Quote Originally Posted by Dark View Post
    Why don't you just use the FileReader/FileWriter instead of ScanXan?
    Actually I re-read this and I am confused. I am using both classes. They're constructed within my class. Can you take a look at the code and give me some indication of why I am not seeing an output in the file? The file is created, but it's empty.

  5. #5
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,557
    Rep Power
    23

    Default

    Observations:
    You have 2 next() calls for 1 hasNext() call
    You don't printStackTrace() to show errors
    you don't close the output file.

  6. #6
    bigsonny is offline Senior Member
    Join Date
    Nov 2010
    Posts
    164
    Rep Power
    4

    Default

    Quote Originally Posted by Norm View Post
    Observations:
    You have 2 next() calls for 1 hasNext() call
    You don't printStackTrace() to show errors
    you don't close the output file.
    Hello Norm,

    I did two of the 3.

    Java Code:
    import java.io.*;
    import java.util.Scanner;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.BufferedReader;
    import java.io.PrintWriter;
    import java.io.IOException;
    
    
    public class ScanXan2 {
        public static void main(String[] args) throws IOException {
    	 		//declaration of a Scanner object named "s" and assigning a null value to it.
            Scanner s = null;
    		  //declaration of a PrintWriter object named "output" and assigning a null value to it.
    		  PrintWriter output = null;
    		  
    		  
            try {
    		  		//the Scanner object s is now constructed with 
                s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
    				output = new PrintWriter (new FileWriter ("xanaduout.txt"));
    				
    				//This first conditional/loop will print to the screen each token, separated by a space
                while (s.hasNext()) {
                    System.out.println(s.next());				 
    					 }
    				//This second conditional/loop will hopefully print to the file.
    				while (s.hasNext()) {
    					output.println(s.next());
    					 }
    				}					 
                
             finally {
    		  		//closing s Scanner
                if (s != null) {
                    s.close();
                }
    				//closing output PrintWriter
    				if (output != null) {
    					output.close();
    				}
            }
        }
    }
    I don't know how to use printStackTrace(). I tried printing it to the screen, but I received the following error:

    Java Code:
    ScanXan2.java:26: cannot find symbol
    symbol  : method printStackTrace(java.lang.String)
    location: class java.io.PrintStream
    					 System.out.printStackTrace(s.next());				 
    					           ^
    1 error
    so I removed it from the code. I went to the API but the first method asks for a
    Java Code:
     catch (HighLevelException e) {e.printStackTrace(); }
    I tried that and instead ended up with the following error:
    Java Code:
    ScanXan2.java:33: cannot find symbol
    symbol  : class HighLevelException
    location: class ScanXan2
    			catch (HighLevelException e) {
    			       ^
    1 error
    so then I tried to system.err.printStackTrace(); and I received two errors, the one above and another cannot find symbol for the .err

    Java Code:
     ----jGRASP exec: javac -g ScanXan2.java
    
    ScanXan2.java:25: cannot find symbol
    symbol  : method printStackTrace()
    location: class java.io.PrintStream
    					 System.err.printStackTrace();
    					           ^
    ScanXan2.java:33: cannot find symbol
    symbol  : class HighLevelException
    location: class ScanXan2
    			catch (HighLevelException e) {
    			       ^
    2 errors
    
     ----jGRASP wedge2: exit code for process is 1.
     ----jGRASP: operation complete.

  7. #7
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,557
    Rep Power
    23

    Default

    Usually like this at end of try{ block:
    Java Code:
    }catch(Exception e) {e.printStackTrace();}

  8. #8
    bigsonny is offline Senior Member
    Join Date
    Nov 2010
    Posts
    164
    Rep Power
    4

    Default

    Thanks. I added it, resulting in the following:

    Java Code:
    import java.io.*;
    import java.util.Scanner;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.BufferedReader;
    import java.io.PrintWriter;
    import java.io.IOException;
    
    
    public class ScanXan2 {
        public static void main(String[] args) throws IOException {
    	 		//declaration of a Scanner object named "s" and assigning a null value to it.
            Scanner s = null;
    		  //declaration of a PrintWriter object named "output" and assigning a null value to it.
    		  PrintWriter output = null;
    		  
    		  
            try {
    		  		//the Scanner object s is now constructed with 
                s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
    				output = new PrintWriter (new FileWriter ("xanaduout.txt"));
    				
    				//This first conditional/loop will print to the screen each token, separated by a space
                while (s.hasNext()) {
                    System.out.println(s.next());
    					 				 
    					 }
    				//This second conditional/loop will hopefully print to the file.
    				while (s.hasNext()) {
    					output.println(s.next());
    					 }
    				}
    				catch (Exception e) {
    					e.printStackTrace();
    					}					 
                
             finally {
    		  		//closing s Scanner
                if (s != null) {
                    s.close();
                }
    				//closing output PrintWriter
    				if (output != null) {
    					output.close();
    				}
            }
        }
    }
    but my output file is still empty. Any other suggestions?

  9. #9
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,557
    Rep Power
    23

    Default

    Are all the lines in the file printed?

    Add a println to show the value of hasNext() at this point in your code:
    Java Code:
                  
                                   System.out.println("hasNext=" + s.hasNext()); // show if more lines
                                   //This second conditional/loop will hopefully print to the file.
    				while (s.hasNext()) {
    					output.println(s.next());
                                     }

  10. #10
    bigsonny is offline Senior Member
    Join Date
    Nov 2010
    Posts
    164
    Rep Power
    4

    Default

    Quote Originally Posted by Norm View Post
    Are all the lines in the file printed?

    Add a println to show the value of hasNext() at this point in your code:
    Java Code:
                  
                                   System.out.println("hasNext=" + s.hasNext()); // show if more lines
                                   //This second conditional/loop will hopefully print to the file.
    				while (s.hasNext()) {
    					output.println(s.next());
                                     }
    Thanks. I added it and it prints false once it runs out, but It is still not printing to the file. I'll think about it and see what I get. thanks!

  11. #11
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,557
    Rep Power
    23

    Default

    Are all the lines in the file printed?

  12. #12
    bigsonny is offline Senior Member
    Join Date
    Nov 2010
    Posts
    164
    Rep Power
    4

    Default

    Quote Originally Posted by Norm View Post
    Are all the lines in the file printed?
    No Norm. The file is created, but there are no lines. No text.

  13. #13
    bigsonny is offline Senior Member
    Join Date
    Nov 2010
    Posts
    164
    Rep Power
    4

    Default

    Hello Norm,

    good news...well sort of. I overcame my semantic error, so the code does what I wanted it to do. I don't think it's the best or the cleanest way to do it, but it's a start in the right direction in terms of problem solving. Please see below:

    Java Code:
    import java.util.Scanner;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.BufferedReader;
    import java.io.PrintWriter;
    import java.io.IOException;
    
    
    public class ScanXan2 {
        public static void main(String[] args) throws IOException {
    	 		//declaration of a Scanner object named "s" and assigning a null value to it.
            Scanner s = null;
    		  Scanner t = null;
    		  //declaration of a PrintWriter object named "output" and assigning a null value to it.
    		  PrintWriter output = null;
    		  
    		  
            try {
    		  		//the Scanner object s is now constructed with 
                s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
    				t = new Scanner(new BufferedReader(new FileReader("Xanadu.txt")));
    				output = new PrintWriter (new FileWriter ("xanaduout.txt"));
    				
    				//This first conditional/loop will print to the screen each token, separated by a space
                                    while (s.hasNext()&& (t.hasNext())) {
                                    System.out.println(s.next());
    				output.println(t.next());
    					 				 
    					 }
    				//This second conditional/loop will hopefully print to the file.
    				System.out.println("hasNext=" + s.hasNext()); // show if more lines
                                   //This second conditional/loop will hopefully print to the file.
    				while (s.hasNext()) {
    					output.println(s.next());
                                     }
    				}
    				catch (Exception e) {
    					e.printStackTrace();
    					}					 
                
             finally {
    		  		//closing s Scanner
                if (s != null) {
                    s.close();
                }
    				//closing output PrintWriter
    				if (output != null) {
    					output.close();
    				}
            }
        }
    }
    So it's all thanks to you actually. The code you gave me where you asked me to check if there is something left to read returned false. So I realize that by time I got to scanning the file and printing it into the new file, there was nothing left outside of the while loop. So I placed it inside the first while look and it still did not work. However I created a second scanner object, I could then printwrite it into the file with each token occupying only one line. Thank you for your help.

    So while I am glad that I got it to do what I wanted, I know the code is somewhat sloppy and perhaps not the best way to about it. Any criticism by anyone is highly welcome. Thanks!

  14. #14
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,557
    Rep Power
    23

    Default

    Java Code:
    while (s.hasNext()&& (t.hasNext())) {
                                    System.out.println(s.next());
    				output.println(t.next());
    Instead of using two streams in parallel, read the line into a string and then show it on the screen and write it to the file:
    Java Code:
                             while (s.hasNext()) {
                                    String nexLine = s.next();   // read the next line
                                    System.out.println(nexLine);    // show on screen
    				output.println(nexLine);     // write to file

  15. #15
    bigsonny is offline Senior Member
    Join Date
    Nov 2010
    Posts
    164
    Rep Power
    4

Similar Threads

  1. Problem: Read and Writing Variables to a txt file!
    By Swiftnsilent in forum New To Java
    Replies: 11
    Last Post: 05-05-2011, 11:40 PM
  2. Replies: 4
    Last Post: 11-03-2010, 06:17 PM
  3. writing in file read from another file..
    By UJJAL DHAR in forum New To Java
    Replies: 6
    Last Post: 05-07-2010, 05:41 PM
  4. Replies: 1
    Last Post: 02-27-2010, 01:29 AM
  5. Replies: 5
    Last Post: 07-30-2008, 09:30 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
  •