954,536 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

saving file in java

i have a method that saves an object to file :

public void Save()
    {
        if (canSave)
        {
         JFileChooser fileChooser = new JFileChooser();
           if (fileChooser.showSaveDialog (this) == JFileChooser.APPROVE_OPTION)
           {
            ObjectOutputStream out;
            try {
                 out = new ObjectOutputStream (new FileOutputStream    (fileChooser.getSelectedFile ()));
                 out.writeObject(this.game);
                 out.close ();  
                 }
            catch (IOException ex) {  }
                         
            JOptionPane.showMessageDialog(null, fileChooser.getSelectedFile(),
                    "game saved",JOptionPane.INFORMATION_MESSAGE);
            }
         canSave = false;
        }
        else
          JOptionPane.showMessageDialog(null,"cannot save game","save error",
                     JOptionPane.ERROR_MESSAGE);  
    }


how can i make it save files with an extension? for example: s.myfile
and the same question about opening files with extension.

emilio
Junior Poster
163 posts since Nov 2007
Reputation Points: 20
Solved Threads: 0
 

From what I understand, all objects are saved as .dat files for Java to reinterpret back into an object during deserialization.

To save files with an extension, I'd assume you'd use FileOutputStream and specify the kind of File you'd like to save.

If you mean to save an Object into a file other than the what's provided by Java, you will most likely have to do a 2-in-1 process of saving the Object as .dat file then opening a new file with the desired extension (Click) then opening a Stream to write bytes to that file, in which you'd have to read bytes from your Object file first then write those bytes to the desired file.

You could save yourself time by making a copy of the object file and attempting to change the extension manually, though I'm not sure if this is entirely recommended (or safe). It may be best to use a program that does this for you - one that Java provides most likely.

Alex Edwards
Posting Shark
972 posts since Jun 2008
Reputation Points: 392
Solved Threads: 109
 

using JFileChooser you can set the type of file that the chooser will open or save to by using a filter HERE the internal link in the JFileChooser tutorial

although i haven't used it, i think that it will serve the purpose

sciwizeh
Posting Pro in Training
457 posts since Jun 2008
Reputation Points: 77
Solved Threads: 23
 

ok i will try. thanks

emilio
Junior Poster
163 posts since Nov 2007
Reputation Points: 20
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You