Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: Writing code to save in a file... help please

  1. #1
    Junior Member
    Join Date
    Mar 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Writing code to save in a file... help please

    I am taking java for a course at school and my assignment is to write my code including the PrintWriter option and make it save to another file. I have written the code, it is running with no errors, but when it is all complete, the code is not being saved to the designated file. Any help is appreciated! Thanks in advance!

    // allows message box to pop up
    import javax.swing.JOptionPane;
    // allows the use of random number generator
    import java.util.Random;
    // allows the print writer and the IO Exception
    import java.io.*;

    class PetFinal {
    public static void main(String[] args) throws IOException

    {


    PrintWriter pet = new PrintWriter("I:\ComClasses\2013SP\gcharles\COM-152-SAS03\rchristensen\Assignment.txt");


    // declaring the names for the integers in the loops
    // random generator int to store the value
    int rantimes;
    // code for random number generator
    Random randomnumbers = new Random();
    // string for first user input loop
    String timesstr;
    // int for the user input loop
    int times;


    PetFinalTest p = new PetFinalTest();

    // telling the code where to get the type, name, and age from
    p.setType(JOptionPane.showInputDialog("What type of pet do you have?"));

    // get pets name
    p.setName(JOptionPane.showInputDialog("What is your pets name?"));

    // Receive the pets age

    p.setAge(JOptionPane.showInputDialog("How old is your pet?"));

    // how many times the pet should be moving
    timesstr =(JOptionPane.showInputDialog("How many times do you want " + p.getName() + " to be " + p.getMove()));

    times =Integer.parseInt(timesstr);


    //Output to the user telling them their pets name, type, and age
    pet.println("My pet is a " + p.getType());
    pet.println("The name of your pet is " + p.getName());
    pet.println("He is " + p.getAge() + " years old");
    pet.println("Your pet will move " + times + " times");
    pet.println(p.getSound());
    pet.println(p.getsit());
    rantimes = randomnumbers.nextInt(10) + 1 ;

    // loop controlled by user
    do
    {
    pet.println(p.getMove());
    // counts down to 0 so we do not have an infinite loop
    times --;
    }
    while (times > 0);// stops at 0

    pet.println("Your pet will move " + rantimes + " times");
    // random number generator loop
    do
    {
    pet.println(p.getMove());
    rantimes = rantimes - 1;

    }
    while (rantimes > 0);

    pet.close();

    }

    }


  2. #2
    Member
    Join Date
    Sep 2012
    Posts
    128
    Thanks
    1
    Thanked 14 Times in 14 Posts

    Default Re: Writing code to save in a file... help please

    PetFinalTest class is missing from the code you posted.

    PrintWriter needs to write, but that part is not here.

    (are you using java 1.7 or and older version?)

  3. #3
    Junior Member
    Join Date
    Mar 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Writing code to save in a file... help please

    Im using jcreator 4.5.... and my professor said we can leave the class file alone, but here it is...:

    // private code
    class PetFinalTest {
    //methods
    private String Type;
    private String Age;
    private String Name;
    private String Sound;
    private String Move;
    private int Go;


    // telling where to call the string type from
    public void setGo(int go)
    {
    Go= go;
    }
    public int getGo ()
    {
    return Go;
    }
    public void setMove(String move)
    {
    Move = move;
    }
    public String getMove()
    {
    return Move;
    }
    public void setSound(String sound)
    {
    Sound = sound;
    }
    public String getSound()
    {
    return Sound;
    }
    public void setType(String type)

    {
    Type = type;
    switch (Type)
    {
    case ("dog"):
    Move = "Running";
    break;
    case ("cat"):
    Move = "Chasing";
    break;
    case ("bird"):
    Move = "Flying";
    break;

    }
    if (type.equalsIgnoreCase("dog"))
    {
    Sound = "woof";
    }
    else if (type.equalsIgnoreCase("cat"))
    {
    Sound = "meow";
    }
    else if (type.equalsIgnoreCase("bird"))
    {
    Sound = "Chirp";
    }
    else
    {
    Sound = "I am making a sound";
    }
    }

    public String getType()
    {
    return Type;
    }
    // where we should get age from
    public void setAge(String age)
    {
    Age = age;
    }
    public String getAge()
    {
    return Age;
    }
    // where we should get name from
    public void setName(String name)
    {
    Name = name;
    }
    public String getName()
    {
    return Name;

    }
    public String getsit()
    {
    return "I'm sitting down";
    }
    }

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,824
    Thanks
    55
    Thanked 2,344 Times in 2,315 Posts

    Default Re: Writing code to save in a file... help please

    Please edit your post and wrap your code with
    [code=java]
    <YOUR CODE HERE>
    [/code]
    to get highlighting and preserve formatting.

    the code is not being saved to the designated file
    Is there a file written anywhere? What is in that file?
    What do you mean by "the code"? Normally the code refers to the source file (the .java file).
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Mar 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Writing code to save in a file... help please

    I have a file named Assignment.txt in the designated folder that i put in my PrintWriter pet = new PrintWriter(......), its a notepad document, and what i mean is that the code is being executed, but what we learned in class is that after you execute the code it will save the output into the designated area instead of the general output window provided with jcreator
     // allows message box to pop up
     import javax.swing.JOptionPane;
     // allows the use of random number generator
     import java.util.Random;
     // allows the print writer and the IO Exception
     import java.io.*;
     
    class PetFinal {
    public static void main(String[] args) throws IOException
     
    {
     
     
    	PrintWriter pet = new PrintWriter("I:\ComClasses\2013SP\gcharles\COM-152-SAS03\rchristensen\Assignment.txt");
     
     
    	// declaring the names for the integers in the loops
    		// random generator int to store the value
    		int rantimes;
    		// code for random number generator
    		Random randomnumbers = new Random(); 
    		// string for first user input loop
    		String timesstr;
    		//  int for the user input loop
    		int times;
     
     
        	PetFinalTest p = new PetFinalTest();
     
        	// telling the code where to get the type, name, and age from
        	p.setType(JOptionPane.showInputDialog("What type of pet do you have?"));
     
        	// get pets name
        	p.setName(JOptionPane.showInputDialog("What is your pets name?"));
     
        	// Receive the pets age
     
        	p.setAge(JOptionPane.showInputDialog("How old is your pet?"));
     
        	// how many times the pet should be moving
        	timesstr =(JOptionPane.showInputDialog("How many times do you want " + p.getName() + " to be " + p.getMove()));
     
        	times =Integer.parseInt(timesstr);
     
     
        	//Output to the user telling them their pets name, type, and age
        	pet.println("My pet is a " + p.getType());
        	pet.println("The name of your pet is " + p.getName());
         	pet.println("He is " + p.getAge() + " years old");
           	pet.println("Your pet will move " + times + " times");
        	pet.println(p.getSound());
       		pet.println(p.getsit());
        	rantimes = randomnumbers.nextInt(10) + 1 ;
     
        	// loop controlled by user
        	do
        	{	
        		pet.println(p.getMove());
        		// counts down to 0 so we do not have an infinite loop
        		times --;
        	    	}
        	while (times > 0);// stops at 0
     
        	pet.println("Your pet will move " + rantimes + " times");
        	// random number generator loop
        	do
        	{
        		pet.println(p.getMove());
        		rantimes = rantimes - 1;
     
        	}
        	while (rantimes > 0);
     
        	 pet.flush();
        	 pet.close();
     
        }
     
    }

    // private code
    class PetFinalTest {
    	//methods
    	private String Type;
    	private String Age;
    	private String Name;
    	private String Sound;
    	private String Move;
    	private int Go;
     
     
    	// telling where to call the string type from
    	public void setGo(int go)
    	{
    		Go= go;
    	}
    	public int getGo ()
    	{
    		return Go;
    	}
    	public void setMove(String move)
    	{
    		Move = move;
    	}
    	public String getMove()
    	{
    		return Move;
    	}
    	public void setSound(String sound)
    	{
    			Sound = sound;
    	}
    	public String getSound()
    	{
    		return Sound;
    		}
    	public void setType(String type)
     
    	{
    			Type = type;
    		switch (Type)
    		{
    			case ("dog"):
    				Move = "Running";
    					break;
    			case ("cat"):
    				Move = "Chasing";
    				break;
    			case ("bird"):
    				Move = "Flying";
    				break;
     
    		}
    		if (type.equalsIgnoreCase("dog"))
    		{
    					Sound = "woof";
    		}
    		else if (type.equalsIgnoreCase("cat"))
    		{	
    			Sound = "meow";
    		}
    		else if (type.equalsIgnoreCase("bird"))
    		{
    			Sound = "Chirp";
    		}
    		else 
    		{
    			Sound = "I am making a sound";
    		}
    	}
     
    	public String getType()
    	{
    		return Type;
    	}
    	// where we should get age from
    	public void setAge(String age)
    	{
    		Age = age;
    	}
    	public String getAge()
    	{
    		return Age;
    		}
    		// where we should get name from
    	public void setName(String name)
    	{
    		Name = name;
    	}
    	public String getName()
    	{
    		return Name;
     
    	}
    	public String getsit()
    	{
    	return "I'm sitting down";
    	}
    	}

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,824
    Thanks
    55
    Thanked 2,344 Times in 2,315 Posts

    Default Re: Writing code to save in a file... help please

    When you execute the code are there any error messages written to the console?
    The use of the throws clause on the main() method means the program will ignore any errors and return the errors to the console.
    public static void main(String[] args)      throws IOException
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Mar 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Writing code to save in a file... help please

    Ok so i just found that in my SRC folder its creating the notepad documents, is there a way to get it to open using just the PrintWriter command? or is what i am telling it to do, executing properly?
    Sorry im so new to java and can't stand it

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,824
    Thanks
    55
    Thanked 2,344 Times in 2,315 Posts

    Default Re: Writing code to save in a file... help please

    its creating the notepad documents
    Is that a file? What are the filenames of the documents?
    get it to open using just the PrintWriter command
    Are you talking about the PrintWriter class that is used to write to files?
    What do you mean by "to open"?
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Mar 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Writing code to save in a file... help please

    when my professor was demonstrating the project, when he finished his code, when it was done executing the notepad document opened itself up... so i thought but i could be wrong
    and for your first question: i just rewrote the code now to just say "PrintWriter pet = new PrintWriter("Assignment.txt");" and it is now saving directly to my src folder and i am able to open it through that.

    I am now wondering if there is a way that the file will open itself rather than having the user go searching for it.

  10. #10
    Member
    Join Date
    Sep 2012
    Posts
    128
    Thanks
    1
    Thanked 14 Times in 14 Posts

    Default Re: Writing code to save in a file... help please

    As I thought, the file path could be wrong. Try changing it from:
    "I:\ComClasses\2013SP\gcharles\COM-152-SAS03\rchristensen\Assignment.txt"
    to
    "I:/ComClasses/2013SP/gcharles/COM-152-SAS03/rchristensen/Assignment.txt"

    Whilst you are debugging, you can write the output to the console so you don't have to check the file every time:
    PrintWriter pet = new PrintWriter(System.out);

    {If you have the latest Java installed, your Prof should be using NIO2 rather than the old IO. Java has improved things.}

  11. #11
    Junior Member
    Join Date
    Mar 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Writing code to save in a file... help please

    I believe i had the assignment doing what the professor needed, so i submitted it. Thanks for your help! I'll be posting on here again I am sure, java really screws me up

  12. #12
    Member
    Join Date
    Feb 2013
    Location
    Canada
    Posts
    54
    Thanks
    0
    Thanked 6 Times in 6 Posts

    Default Re: Writing code to save in a file... help please

    If you already submitted your assignment, it's too late to add this but for future reference, your main method contains "throws IOException" but no where in the method do you use either a try-catch-finally block or throw a new exception object. If an error occurs, it will print directly to the console, but you may want to handle it differently, such as a pop-up message via JOptionPane.

    Quote Originally Posted by rchrist3 View Post
    I am now wondering if there is a way that the file will open itself rather than having the user go searching for it.
    The PrintWriter class has a .close() method to close the stream but it cannot open the actual notepad document. It is, however, possible to write a separate Java class for it or use something else, such as shell scripting (or PowerShell). Easiest though would be to just open the notepad document yourself.

Similar Threads

  1. help me to save file with io
    By vijay1807 in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: September 10th, 2012, 10:01 AM
  2. Save results in an excel file
    By helensyk in forum What's Wrong With My Code?
    Replies: 1
    Last Post: July 31st, 2012, 10:43 AM
  3. counting the values in input file and and writing the output to a file
    By srujirao in forum What's Wrong With My Code?
    Replies: 3
    Last Post: July 8th, 2012, 03:48 PM
  4. trying to save data onto a file
    By DanTheSand in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: December 13th, 2011, 09:58 AM
  5. How to save statistics of a game in a binary file instead of txt file?
    By FretDancer69 in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: June 19th, 2009, 06:05 AM