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.

Page 1 of 2 12 LastLast
Results 1 to 25 of 35

Thread: Help writing to a file getting an exception error

  1. #1
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Help writing to a file getting an exception error

    I have program i am trying to do. I was successful in checking to see if the file was created and if it was not created then creating it. Now I want to actually put data it the file and i am getting an exception error. Writing to a file should be very easy. Not sure where I am going wrong with this.
    import java.io.File;
    import java.io.*;
    import java.util.Formatter;
    import java.util.Scanner;
     
    /**
     *
     * @author Jamal
     */
    public class Player {
     
        private int wonAGame;
        private int lostAGame;
        private int addMoney;
        private static String fPlayer;
        private Formatter x;
        Scanner sn = new Scanner(System.in);
     
        public String getPlayerinfo() {
     
            return fPlayer;
        }
     
        public void playerInfo(String fName) {
            System.out.println("Please enter your first name: ");
            String fname = sn.nextLine();
            fPlayer = fname;
            Player pr = new Player();
            pr.checkPlayer(fname);
        }
     
        public void checkPlayer(String fname) {
            File file = new File("C:\\test\\" + fPlayer + ".txt");
     
            if (file.exists()) {
     
                System.out.println("Weclome back" + " " + fPlayer);
            } else {
                System.out.println("Sorry not there");
     
     
                try {
                    Formatter x = new Formatter("C:\\test\\" + fPlayer + ".txt");
                    System.out.println("File has been created");
                } catch (Exception e) {
                    System.out.println("didn't work");
                }
                Player pr = new Player();
                pr.writeFile();
     
            }
        }
     
        public void writeFile() {
            x.format("%s,%s", "LastName, First Name");
     
     
        }
     
        public void closeFile() {
            x.close();
        }
    }
    Last edited by loui345; September 27th, 2012 at 10:35 PM.


  2. #2
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Help writing to a file getting an exception error

    made a mistake on tags, can someone instruct me again on how to do tags

  3. #3
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Help writing to a file getting an exception error

    See my signature.
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  4. #4
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Help writing to a file getting an exception error

    Also, can you provide more information including exact errors and code which errors refer to.
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  5. #5
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Help writing to a file getting an exception error

    To guide you through this, I've made a quick demo of how you can write to a file using Formatter.

    import java.io.File;
    import java.util.Formatter;
     
    public class FormatterTest {
     
        public static void main(String[] args) throws Exception {
    	final String fileName = "output.txt";
    	final File destination = new File(fileName);
     
    	if (!destination.exists()) {
    	    destination.createNewFile();
    	}
     
    	final Formatter formatter = new Formatter(destination);
    	formatter.format("%s ####### %s", "Hello", "World");
    	formatter.flush();
    	formatter.close();
     
        }
     
    }

    The reason I'm showing you this is so you can get to grips of what is needed to make a Formatter object do what you want.
    There are numerous issues with your code, so by starting with cleaning up your Formatter implementation everything can go smoother.

    Have a go with that, tweak your program and ask away when you've hit a brick wall.
    With regards to your other problems, don't create multiple Player objects within a single Player object, refer to your methods directly inside the class, such as call writeFile(); instead of making a new player and calling pr.writeFile();
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  6. #6
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Help writing to a file getting an exception error

    I got it work thanks newbie. SO my problem was that I had many objects of the same class. I should of just created a new object to write to the file?

  7. #7
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: Help writing to a file getting an exception error

    Please attempt to format your code so that we can read it. It's difficult trying to understand someone else's code, why make it more harder than it has to be?

    I usually use [code=java] [/code]

  8. #8
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Help writing to a file getting an exception error

    Now I got the problem to work following newbie's advice. I just would like to know where my thinking went bad, so in the future I won't make this mistake, and possibly I can apply this logic to future problems.

  9. #9
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Help writing to a file getting an exception error

    Hello,

    I have gotten my program to work and do what I desire, but I still am getting java.lang.illegalStateException: Scanner closed error. The program is doing what it is suppose to be doing, but I don't understand on why I am getting an error. I believe it has to do with me closing the scanner, but I am unsure on how to properly close the scanner. Can someone please explain to me why this is giving me an error!!

    public class Player {
     
        private int wonAGame;
        private int lostAGame;
        private int addMoney;
        private static String fPlayer;
        Scanner sn = new Scanner(System.in);
     
        public String getPlayerinfo() {
     
            return fPlayer;
        }
     
        public void playerInfo(String fName) {
            System.out.println("Please enter your first name: ");
            String fname = sn.nextLine();
            fPlayer = fname;
            Player pr = new Player();
            pr.checkPlayer(fname);
        }
     
        public void checkPlayer(String fname) {
            File file = new File("C:\\test\\" + fPlayer + ".txt");
     
            if (file.exists()) {
     
                System.out.println("Weclome back" + " " + fPlayer);
                Player pr = new Player();
                pr.readFile();
            } else {
                System.out.println("Sorry not there");
                System.out.println("Would you like you to create a new file to start to play the game (1 = yes, 2 = no)?");
                int playerResponse = sn.nextInt();
                while (2 <= playerResponse) {
     
                    System.out.println("Would you like you to create a new file to start to play the game (1 = yes, 2 = no)?");
     
                    playerResponse = sn.nextInt();
                }
                if (playerResponse == 1) {
                    System.out.println("Please enter your first name");
                    Scanner ms = new Scanner(System.in);
                    String Fplayer = ms.nextLine();
                    System.out.println("Please enter your amount of money");
                    int amountMoney = ms.nextInt();
                    System.out.println("Welcome new Player");
                    System.out.println("Please enter your information below");
                    Player pr = new Player();
                    pr.writeFile(Fplayer, amountMoney);
                }
     
                try {
                    Formatter x = new Formatter("C:\\test\\" + fPlayer + ".txt");
                    System.out.println("File has been created");
                } catch (Exception e) {
                    System.out.println("didn't work");
                }
                Player pr = new Player();
     
     
            }
        }
     
        public void writeFile(String FPlayer, int Money) {
            try {
                Formatter formatter = new Formatter("C:\\test\\" + fPlayer + ".txt");
     
                formatter.format("%s  %s", FPlayer, Money);
     
     
                formatter.flush();
                formatter.close();
            } catch (Exception e) {
                System.out.println("didn't work");
            }
            Player pr = new Player();
            pr.readFile();
        }
     
        public void readFile() {
     
            try {
                sn = new Scanner(new File("C:\\test\\" + fPlayer + ".txt"));
     
     
            } catch (Exception e) {
                System.out.println("could not find file");
            }
     
            while (sn.hasNext()) {
                String a = sn.next();
                String b = sn.next();
                  sn.close();
                System.out.print("Hi"+" "+a+"\n"+"In your account you've this amount of money"+" "+b);
     
     
     
            }
     
        }
            public void closefile(){
                sn.close();
            }
        }
    Last edited by loui345; September 28th, 2012 at 10:40 PM. Reason: Tags

  10. #10
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Help writing to a file getting an exception error

    I am having trouble closing the scanner

  11. #11
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: Help writing to a file getting an exception error

    Regarding:
            while (sn.hasNext()) {
                String a = sn.next();
                String b = sn.next();
                  sn.close();
                System.out.print("Hi"+" "+a+"\n"+"In your account you've this amount of money"+" "+b);
            }

    A very useful technique is to mentally step through your program "running" each line of code in your head as if you were the JVM. I recommend that you do this for this loop, and see what happens to your Scanner object when you do this. Based on your findings from this exercise, where would be the best code location to close your Scanner object?

  12. #12
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Help writing to a file getting an exception error

    Yes, that makes perfect sense to close the scanner after the loop is done accessing the variables, but I have tried to close the scanner after the System.out.print and still to no avail. For example, when I move the sn.close method the program works without the error, it creates the the file, but no data is stored on it. If I leave the "sn.close" it's location I get the error, but it actually writes to the text file. So I am really unsure on why this is occurring.

  13. #13
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Help writing to a file getting an exception error

    So it appears, I can continue on with the program logic and continue on with game, keep passing the error to other methods, and each method ducks the error, but inevitability it will throw the exception. I just cant' figure out to close the scanner correctly, when I do try and close the scanner outside of the while loop the program works but it doesn't write the code in the text file.

    I feel would like to actually understand where my logic is failing me in this program. I am pleased that you're trying to help me.

    Thanks.

  14. #14
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: Help writing to a file getting an exception error

    Quote Originally Posted by loui345 View Post
    Yes, that makes perfect sense to close the scanner after the loop is done accessing the variables, but I have tried to close the scanner after the System.out.print and still to no avail.
    If you've made this attempt, you should show the code. For we know you still could be trying to close the Scanner inside of the for loop (after the System.out.println but before the closing brace), and only your code will show us if you're making this mistake. We can't help with what we can't see.

  15. #15
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Help writing to a file getting an exception error

    public class Player {
     
        private int wonAGame;
        private int lostAGame;
        private int addMoney;
        private static String fPlayer;
        Scanner sn = new Scanner(System.in);
     
        public String getPlayerinfo() {
     
            return fPlayer;
        }
     
        public void playerInfo(String fName) {
            System.out.println("Please enter your first name: ");
            String fname = sn.nextLine();
            fPlayer = fname;
            Player pr = new Player();
            pr.checkPlayer(fname);
        }
     
        public void checkPlayer(String fname) {
            File file = new File("C:\\test\\" + fPlayer + ".txt");
     
            if (file.exists()) {
     
                System.out.println("Weclome back" + " " + fPlayer);
                Player pr = new Player();
                pr.readFile();
            } else {
                System.out.println("Sorry not there");
                System.out.println("Would you like you to create a new file to start to play the game (1 = yes, 2 = no)?");
                int playerResponse = sn.nextInt();
                while (2 <= playerResponse) {
     
                    System.out.println("Would you like you to create a new file to start to play the game (1 = yes, 2 = no)?");
     
                    playerResponse = sn.nextInt();
                }
                if (playerResponse == 1) {
                    System.out.println("Please enter your first name");
                    Scanner ms = new Scanner(System.in);
                    String Fplayer = ms.nextLine();
                    System.out.println("Please enter your amount of money");
                    int amountMoney = ms.nextInt();
                    System.out.println("Welcome new Player");
                    System.out.println("Please enter your information below");
                    Player pr = new Player();
                    pr.writeFile(Fplayer, amountMoney);
                }
     
                try {
                    Formatter x = new Formatter("C:\\test\\" + fPlayer + ".txt");
                    System.out.println("File has been created");
                } catch (Exception e) {
                    System.out.println("didn't work");
                }
                Player pr = new Player();
     
     
            } 
        }
     
        public void writeFile(String FPlayer, int Money) {
            try {
                Formatter formatter = new Formatter("C:\\test\\" + fPlayer + ".txt");
     
                formatter.format("%s  %s", FPlayer, Money);
     
     
                formatter.flush();
                formatter.close();
            } catch (Exception e) {
                System.out.println("didn't work");
            }
            Player pr = new Player();
            pr.readFile();
        }
     
        public void readFile() {
     
            try {
                sn = new Scanner(new File("C:\\test\\" + fPlayer + ".txt"));
     
     
            } catch (Exception e) {
                System.out.println("could not find file");
            }
           //Right here is where the error is occuring
           // "main" java.lang.IllegalStateException: Scanner closed
            while (sn.hasNext()) {
                String a = sn.next();
                String b = sn.next();
     
     
                System.out.print("Hi"+" "+a+"\n"+"In your account you've this amount of money"+" "+b);
                Dice ce = new Dice();
                ce.diceGenerator(b);
               sn.close();
     
     
     
            }
     
        }
            public void closefile(){
                sn.close();
            }
        }

    I am having trouble with closing the scanner. If I remove the method to close the scanner, the program will function correctly but it won't write to the text pad. Scanner does read the text pad as if information was actually written, but there is no data. If I leave the method to close the scanner in that place it works perfectly, I just have an exception error. I honestly don't know how to fix it. So can someone please explain where my logic is wrong.

  16. #16
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: Help writing to a file getting an exception error

    Again, you're closing your scanner inside of your while loop. Note that the while loop begins on the line with the while ( ... ) { and ends at the matching closing brace, }:

    while (sn.hasNext()) {
      // all code from here
     
      String a = sn.next();
      System.out.print("Hi"+" "+a+"\n"+"In your account you've this amount of money"+" "+b);
      Dice ce = new Dice();
      ce.diceGenerator(b);
      sn.close();
     
      // to here are inside the while loop
    }

    All code inside the two braces are inside of the loop. Logic will tell you that since you're using the Scanner as part of your while boolean test, that you cannot close it inside of the loop. Logic will tell you the trivial solution: close the Scanner object outside of the loop, after the while loops closing curly brace, }.

    while (sn.hasNext()) {
      String a = sn.next();
      System.out.print("Hi"+" "+a+"\n"+"In your account you've this amount of money"+" "+b);
      Dice ce = new Dice();
      ce.diceGenerator(b);
    }
    sn.close();

    A key learning point to use of the forum: always try to illustrate what you're doing by showing the pertinent code. It really is worth a thousand words and would have saved a lot of time if shown earlier.
    Last edited by curmudgeon; September 29th, 2012 at 07:41 PM.

  17. #17
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Help writing to a file getting an exception error

    Yes,

    I understand the point you're trying to make, but if I close the scanner outside of the while loop the program will not write to the text file. I end up with a blank text file. Leaving my scanner in the place that you see allows me to write the data to the text file, but the result of that is that I am getting an exception error. Does this make sense to you?

  18. #18
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: Help writing to a file getting an exception error

    OK, let me look at the rest of your code in greater depth...

  19. #19
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: Help writing to a file getting an exception error

    Your code confuses me quite a bit, and part of it is because of your god-class, Player, since it seems full of lots of code that has little to do with the essence of being a Player object. I think that you need to first do some serious refactoring here, some cleaning up. I'd make Player just responsible for the essence of being a Player -- meaning it has a name, money, perhaps a record of games won and lost, methods and constructors to set and change this information and extract this information and that's it. Something like this:

    class Player2 {
       private String name;
       private int money;
     
       public Player2(String name, int money) {
          this.name = name;
          this.money = money;
       }
     
       public Player2(String name) {
          this(name, 0);      
       }
     
       public String getName() {
          return name;
       }
     
       public int getMoney() {
          return money;
       }
     
       // could add negative amount if want to
       // take money
       public void addMoney(int add) {
          // ...
       }
     
       @Override
       public String toString() {
          // .... return a String that has the properties of this object
       }
     
    }

    And then I'd create another class, say PlayerIO that simply concerns itself with IO aspects including writing the Player data to disk and reading it out again. Then I'd create another class called Game that was involved with creating a Player or two, setting up the game and having Player play the game.

  20. #20
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Help writing to a file getting an exception error

    Okay, great I totally understand your logic, but if i still clean the code up I still don't understand where I went wrong with scanner method. It works as long as the close is in the while loop.

    I will clean the code up as you suggested, but I don't to comeback in a few hours with the same question I had before.

    Again, thanks for taking the time to help me.

  21. #21
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: Help writing to a file getting an exception error

    Quote Originally Posted by loui345 View Post
    Okay, great I totally understand your logic, but if i still clean the code up I still don't understand where I went wrong with scanner method. It works as long as the close is in the while loop.
    I'm not sure either because your code is going every which way but loose. For instance when you read the Player data in in the readFile() method, where do you save it to a variable that is available to the class *anywhere*?

  22. #22
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Help writing to a file getting an exception error

    Yes, I saved the data to into Strings using the scanner next method, which seems to work.

  23. #23
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: Help writing to a file getting an exception error

    Quote Originally Posted by loui345 View Post
    Yes, I saved the data to into Strings using the scanner next method, which seems to work.
    But where do you save this data as I don't see it in the readFile() method that you've posted? And besides, the Player information should be saved as a Player object, not Strings, right?

  24. #24
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Help writing to a file getting an exception error

    I am sorry, i misunderstood you. My intentions was to read the text file store the information into variables, which then would allow me to manipulate the data. That what I thought you was asking earlier. I am unsure on what you're asking me about my readFile method.

  25. #25
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: Help writing to a file getting an exception error

    The question is what is the purpose of the readFile()? Is to simply print out what is held in the file, to just display it? Or is it to convert the data held into Player objects? Because if the latter, it does nothing of the kind.

    Regardless, you will need to do some serious refactoring and cleaning of that code.

Page 1 of 2 12 LastLast

Similar Threads

  1. 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, 02:48 PM
  2. new line in file writing
    By deependeroracle in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: January 30th, 2012, 09:06 AM
  3. Error writing to an array with the static modifier.
    By handuel in forum Collections and Generics
    Replies: 2
    Last Post: December 25th, 2011, 10:10 AM
  4. Need Help Writing Exception code.
    By USCPaddler in forum Exceptions
    Replies: 4
    Last Post: November 10th, 2011, 05:45 PM
  5. file reading & writing
    By macko in forum What's Wrong With My Code?
    Replies: 7
    Last Post: May 12th, 2011, 08:54 AM