Results 1 to 4 of 4
  1. #1
    LifeWithJava is offline Member
    Join Date
    Dec 2008
    Posts
    7
    Rep Power
    0

    Default Using Printwriter (java.io.*)

    Hi' all,

    I have a problem trying to get my program to read names from the user and store them in a file. I did some debugging and managed to narrow it down to my use of the pwStream variable, would appreciate any help on this:

    CODE:

    /** Purpose: To learn how to use the java io package and incorporate exception handling in the program. Specifically, I am trying to get my program to request the user for 3 names, and store the names in a file called 'NAMES.txt'.
    */

    import java.util.*;
    import java.io.*;

    public class Test
    {
    public static void main(String [] args)
    {
    try
    {
    PrintWriter pwStream= new PrintWriter(new BufferedWriter (new FileWriter ("NAMES.txt")));
    Scanner sc=new Scanner(System.in);
    String str=null;
    System.out.println("Please enter 3 names to be stored in the file: ");

    for (int i=0;i<3;i++)
    {
    str=sc.next();
    //System.out.println(str);
    pwStream.println(str); // here is where my problem is, after execution, the file NAMES.txt contains no names
    }


    }
    catch (IOException e)
    {
    System.out.println("Error!" );
    }

    }
    }

    END OF CODE

    Thanks for helping :)

    p.s. sorry bout the indents, i cant get my program to be indented when it is published here, got to figure that one out.
    Last edited by LifeWithJava; 12-24-2008 at 07:07 AM.

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    14

    Default

    Java Code:
                for (int i=0;i<3;i++)
                {
                    System.out.println("enter name " + (i+1));
                    str=sc.nextLine();
                    //System.out.println(str);
    cant get my program to be indented when it is published here
    &#91;code&#93;
    // paste code here
    &#91;/code&#93;

  3. #3
    mtyoung is offline Senior Member
    Join Date
    Dec 2008
    Location
    Hong Kong
    Posts
    473
    Rep Power
    11

    Default

    you need to Flush the stream after all your write method call

  4. #4
    LifeWithJava is offline Member
    Join Date
    Dec 2008
    Posts
    7
    Rep Power
    0

    Default

    Thanks guys, I needed to use the flush and close method. problem solved. thanks!

Posting Permissions

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