Results 1 to 15 of 15
  1. #1
    Raian is offline Member
    Join Date
    May 2010
    Posts
    4
    Rep Power
    0

    Default Creating Ouput Text File

    I'm having trouble with how to generate 10 random numbers between 50 and 100 and write them to a text file.

    this is what i got so far..i'm stuck at the part: output to a text file
    Please help me, give me some ideas or advice on how to fix it or doing it.
    Thanks in advance.

    Java Code:
    import java.io.*;
    import java.util.Random;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    
    public class Project7PartB {
    
       public static void main(String args[])
            {              
                    FileOutputStream out; // declare a file output object
                    
                    try
                    {
                    	
    						// Create a new file output stream
                            // connected to "myfile.txt"
                            out = new FileOutputStream("myfile.txt");
    
                            // Connect print stream to the output stream
                            Rand = new PrintStream( out );
                            Random randomnumber = new Random();
    						int yes[] = new int[10];
    						for(int i=0; i < 10; i++) {
    						yes[i] = randomnumber.nextInt(51) + 50;
    						System.out.println(yes[i]);
    						}
                    }
                    
                    catch (Exception e){
                            System.err.println ("Error writing to file");
                    }
            }
    }
    Moderator Edit: Code tags added
    Last edited by Fubarable; 05-23-2010 at 02:47 PM. Reason: Moderator Edit: Code tags added

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Hello, and welcome to the forum. I hope you don't mind that I edited your code and added code tags which should help make your posted code retain its formatting and be more readable.

    To do this yourself, highlight your pasted code (please be sure that it is already formatted when you paste it into the forum; the code tags don't magically format unformatted code) and then press the code button, and your code will have tags.

    Another way to do this is to manually place the tags into your code by placing the tag [cod&#101;] above your pasted code and the tag [/cod&#101;] below your pasted code like so:

    Java Code:
    [cod&#101;]
      // your code goes here
      // notice how the top and bottom tags are different
    [/cod&#101;]
    Best of luck, and again, welcome!

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Have a look at the Sun input and output tutorials which you can find here: Lesson: Basic I/O

    In particular, check out the sections on character output.

    Much luck!

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

    Default

    Java Code:
    import java.util.Random;
    
    import java.io.FileWriter;
    import java.io.BufferedWriter;
    import java.io.IOException;
    
    public class Project7 {
    	
    	static final String fileName = "myfile.txt";
    	
    	public static void main(String[] args) {
    		try {
    		BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
    		 Random randomNumber = new Random();
    		 int[] yes = new int[10];
    		 String value;
    		 for(int i = 0; i < 10; i++) {
    			 yes[i] = randomNumber.nextInt(51) + 50; 
    			 value = Integer.toString(yes[i]);
    			writer.write(value + " ");
    			}
    		 writer.close();
    		
    		} catch(IOException e) {
    			e.printStackTrace();
    			System.exit(1);
    			} 
    	}
    }

  5. #5
    erakhman is offline Member
    Join Date
    May 2010
    Posts
    14
    Rep Power
    0

    Default

    Java Code:
    import java.io.*;
    import java.util.Random;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    
    public class Project7PartB {
    
    	public static void main(String args[]) {
    
    		FileOutputStream out; // declare a file output object
    		PrintStream Rand; // declare variable Rand
    		try {
    			// Create a new file output stream
    			// connected to "myfile.txt"
    			out = new FileOutputStream("myfile.txt");
    			// Connect print stream to the output stream
    			Rand = new PrintStream( out );
    			Random randomnumber = new Random();
    			int yes[] = new int[10];
    			for(int i=0; i < 10; i++) {
    				yes[i] = randomnumber.nextInt(51)+ 50;
    				System.out.println(yes[i]); // Write output to consule 
    				Rand.println(yes[i]); // Write output to file 
    			}
    		}
    		catch (Exception e){
    			System.err.println ("Error writing to file");
    		}
    
    	}
    
    }

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    cselic closes his writer but erakhman doesn't. This may seem like a small point, but if you have enough of this sort of thing going on in a program, you'll risk running out of resources. I would recommend to both that the BufferedWriter be closed in a finally block after checking that it's not null.

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

    Default

    Well, I have problem with finally block.

    if I write something like this:

    Java Code:
    } catch(IOException e) {
    			e.printStackTrace();
    			System.exit(1);
    			} finally {
    				writer.close();
    			}
    	}
    Then I have error:
    "The local variable writer may not have been initialized
    Unhandled exception type IOException"

  8. #8
    erakhman is offline Member
    Join Date
    May 2010
    Posts
    14
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    cselic closes his writer but erakhman doesn't. This may seem like a small point, but if you have enough of this sort of thing going on in a program, you'll risk running out of resources. I would recommend to both that the BufferedWriter be closed in a finally block after checking that it's not null.
    Thanks moderator, now i have completed my code :

    Java Code:
    import java.io.*;
    import java.util.Random;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    
    public class Project7PartB {
    
    	public static void main(String args[]) {
    
    		FileOutputStream out=null; // declare a file output object
    		PrintStream Rand; // declare variable Rand
    		try {
    			// Create a new file output stream
    			// connected to "myfile.txt"
    			out = new FileOutputStream("myfile.txt");
    			// Connect print stream to the output stream
    			Rand = new PrintStream( out );
    			Random randomnumber = new Random();
    			int yes[] = new int[10];
    			for(int i=0; i < 10; i++) {
    				yes[i] = randomnumber.nextInt(51)+ 50;
    				System.out.println(yes[i]); // Write output to consule 
    				Rand.println(yes[i]); // Write output to file 
    			}
    		}
    		catch (Exception e){
    			System.err.println ("Error writing to file");
    		}
    		finally {
    			try {
    				out.close(); // Close file
    			}
    			catch (Exception e) {
    				System.err.println ("Error close file");
    			}
    		}
    
    	}
    
    }
    Last edited by erakhman; 05-23-2010 at 05:48 PM.

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by erakhman View Post
    Thanks moderator, now i have completed my code :
    Sorry for nit-picking, and I'm no pro at this either, but I'd still modify this further by checking that out isn't null first before closing it and would try to use the most specific exception possible:

    Java Code:
        try {
    
          //...... code deleted for sake of brevity
    
        } catch (FileNotFoundException e) {
          System.err.println("Error writing to file");
          e.printStackTrace();
        } finally {
          try {
            if (out != null) {
              out.close();
            }
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
    As always, corrections are most welcome!

  10. #10
    erakhman is offline Member
    Join Date
    May 2010
    Posts
    14
    Rep Power
    0

    Default

    Ok, i think you're right, thanks ya...

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

    Default

    Java Code:
    Code:
        try {
    
          //...... code deleted for sake of brevity
    
        } catch (FileNotFoundException e) {
          System.err.println("Error writing to file");
          e.printStackTrace();
        } finally {
          try {
            if (out != null) {
              out.close();
            }
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
    On this way my compiler continue to report an error, and requires writting another IOException.
    Something like this:

    Java Code:
    try {
    
    } catch(FileNotFoundException e) {
    
    } [B][COLOR="Purple"]catch(IOException e) {
    }[/COLOR][/B] finally {
          try {
            if (out != null) {
              out.close();
            }
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
    Last edited by cselic; 05-23-2010 at 10:35 PM.

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

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

    Default

    Don't leave your catch block empt
    I don't leave them empty. I did it for simplicity ;)
    Sorry.

    Complete code:
    Java Code:
    } catch (FileNotFoundException e) {
    		      System.err.println("Error writing to file");
    		      e.printStackTrace();
    		    } [B][COLOR="Navy"]catch(IOException e) {
    		    	e.printStackTrace();
    		    }[/COLOR][/B] finally {
    		      try {
    		        if (writer != null) {
    		          writer.close();
    		        }
    		      } catch (IOException e) {
    		        e.printStackTrace();
    		      }
    		    }

  14. #14
    erakhman is offline Member
    Join Date
    May 2010
    Posts
    14
    Rep Power
    0

    Default

    try edit your code, like this :

    Java Code:
    public static void main(String[] args) {
    		BufferedWriter writer = null;
    		try {
    		writer = new BufferedWriter(new FileWriter(fileName));

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

    Default

    Java Code:
    try edit your code, like this
    Code is already written on that way. And it still need another catch with IOException.
    I think it's much better to me to take care of one more exception. :cool:

Similar Threads

  1. creating a graph from a text file
    By chinolee in forum New To Java
    Replies: 3
    Last Post: 11-23-2009, 09:36 AM
  2. Creating&Saving as a different Text file
    By right2001 in forum New To Java
    Replies: 2
    Last Post: 04-07-2009, 08:17 AM
  3. want sql Query ouput in the calling HTML Form.. Pls Help
    By Faheem_Ahmed in forum Advanced Java
    Replies: 2
    Last Post: 03-05-2009, 09:08 PM
  4. find and replace text from a text file
    By gezzel in forum New To Java
    Replies: 2
    Last Post: 09-19-2008, 05:04 PM
  5. creating a text based game
    By Phobos0001 in forum New To Java
    Replies: 1
    Last Post: 02-12-2008, 05:35 PM

Posting Permissions

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