Friday, 8 February 2013

File Handling In Java

File Handling and Saving Score

The following code is used to save the players score to the same folder as the eclipse project called "Scores.txt"

if(UserInput.equals("SAVE")){
    FileOutputStream out; // declare a file output object
                PrintStream p; // declare a print stream object
                try
                {
                        // Create a new file output stream
                        // connected to "myfile.txt"
                        out = new FileOutputStream("Scores.txt");
                        // Connect print stream to the output stream
                        p = new PrintStream( out );
 
                        p.println ("Name: " + PName + " Score: " + PScore);
                        p.close();
                }
                catch (Exception e)
                {
                        System.err.println ("Error writing to file");
                }