Welcome to Dream.In.Code
Getting Java Help is Easy!

Join 107,638 Java Programmers for FREE! Ask your question and get quick answers from experts. There are 987 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!



JFileChooser

 
Reply to this topicStart new topic

JFileChooser, Save Location of Opened File for Future Use

dewjunkie
post 2 Jul, 2008 - 03:31 PM
Post #1


New D.I.C Head

*
Joined: 6 Mar, 2008
Posts: 32

Hey all!

I was hoping that someone could help me out with something.

I am using JFileChooser and I have noticed that it defaults into my Documents and Settings Folder to select a file to open. I was wondering if anyone knew how I could save the folder that I selected a file from for the next time I opened a file. For instance, if I navigated to my MyPictures folder and opened an image file, how would I get it to save that location for next time I opened a file????

Thanks!!

Here's my JFileChooser code:

CODE

    private class OpenImage implements ActionListener{
        @ Override
        public void actionPerformed(ActionEvent event){

            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter(
                    "JPG, GIF, & PNG Images", "jpg", "gif", "png");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(parent);
            if(returnVal == JFileChooser.APPROVE_OPTION) {
                System.out.println("You chose to open this file: " +
                        chooser.getSelectedFile().getName());

                try {
                    Image img = ImageReadWrite.read(chooser.getSelectedFile());
                    ImageFrame iFrame = new ImageFrame(img);
                    deskPane.add(iFrame);
                    iFrame.setVisible(true);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }            
        }            
    }
User is offlineProfile CardPM

Go to the top of the page


pbl
post 2 Jul, 2008 - 03:57 PM
Post #2


D.I.C Lover

Group Icon
Joined: 6 Mar, 2008
Posts: 1,883



Thanked 111 times

Dream Kudos: 75
My Contributions


When you get the File, fetch its directory
CODE

  File file = chooser.getSelectedFile();
  File directory = file.getParent();


Then write the directory into a file
CODE

try {
   ObjectOutputStream oos = new ObjectOutputStream("LastCall.txt");
   oos.writeObject(directory);
   oos.close();
}
catch(IOException e) {
}


Next time

CODE

File directory = null;     // init to null
try {
   ObjectInputStream ois = new ObjectInputStree=am("LastCall.txt");
   directory = (File) ois.readObject();
   ois.close();
}
catch (IOException e) {    // OK no file
}

JFileChooser chooser;
if(directory = null)
   chooser = new JFileChooser();                     // first call
else
   chooser = new JFileChooser(directory);        // last directory saved

User is offlineProfile CardPM

Go to the top of the page

dewjunkie
post 2 Jul, 2008 - 06:16 PM
Post #3


New D.I.C Head

*
Joined: 6 Mar, 2008
Posts: 32

Wow, thx pbl you are awesome! I think I almost have this now. A couple things I am not sure about.
I know that I am writing my current directory to a text file because I found the text file and the directory is there.
I am obviously a java noob so if you could help me fix my bugs that'd be sweet! I think my problems are where I added //******* to the code.

CODE

    private class OpenImage implements ActionListener{
        @ Override
        public void actionPerformed(ActionEvent event){

            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter(
                    "JPG, GIF, & PNG Images", "jpg", "gif", "png");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(parent);
            if(returnVal == JFileChooser.APPROVE_OPTION) {
                System.out.println("You chose to open this file: " +
                        chooser.getSelectedFile().getName());

                
                try {
                    Image img = ImageReadWrite.read(chooser.getSelectedFile());
                    ImageFrame iFrame = new ImageFrame(img);
                    deskPane.add(iFrame);
                    iFrame.setVisible(true);

                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                File file = chooser.getSelectedFile();
                
                                 // ******* When I tried to make this next line File directory it threw me a type mismatch so
                                 // ******* I changed it to a string I don't think that was right.
                                String directory = file.getParent();
                System.out.println(directory);

                try {

                    FileOutputStream fos = new FileOutputStream("LastCall.txt");
                    ObjectOutputStream oos = new ObjectOutputStream(fos);
                    oos.writeObject(directory);
                    oos.close();
                }
                catch(IOException e) {
                }


                     // init to null
                try {
            
                    FileInputStream fis = new FileInputStream("LastCall.txt");
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    directory = (String)ois.readObject();
                    
                    ois.close();
                    
                }
                catch (IOException e) {    // OK no file
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
                                // ***** Then when you said to set the File directory to null that duplicated a local variable
                directory = null;

                                // ***** I think it was just a typo but you had directory = null, not ==.
                if(directory == null)
                    chooser = new JFileChooser(directory);                     // first call
                else
                    chooser = new JFileChooser();  

            }            
        }            
    }

User is offlineProfile CardPM

Go to the top of the page

pbl
post 2 Jul, 2008 - 06:32 PM
Post #4


D.I.C Lover

Group Icon
Joined: 6 Mar, 2008
Posts: 1,883



Thanked 111 times

Dream Kudos: 75
My Contributions


Sorry my mistake

File directory = file.getParentFile(); // not getParent() that returns a String

Should really test my code before posting but wanted to answer fast
You will also have to catch a Class catch exception so easier to test both in one statment

CODE

try {
   ObjectInputStream ois = new ObjectInputStree=am("LastCall.txt");
   directory = (File) ois.readObject();
   ois.close();
}
catch (Exception e) {    // OK no file or cast error <------- Exception instead of IOException
}


This post has been edited by pbl: 2 Jul, 2008 - 06:38 PM
User is offlineProfile CardPM

Go to the top of the page

dewjunkie
post 2 Jul, 2008 - 07:12 PM
Post #5


New D.I.C Head

*
Joined: 6 Mar, 2008
Posts: 32

You seriously are the man! Consider yourself thanked! Just 2 little minor things and I think it'll run. The 2 things are in my code with //*********** marking them.

CODE

    private class OpenImage implements ActionListener{
        @ Override
        public void actionPerformed(ActionEvent event){

            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter(
                    "JPG, GIF, & PNG Images", "jpg", "gif", "png");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(parent);
            if(returnVal == JFileChooser.APPROVE_OPTION) {
                System.out.println("You chose to open this file: " +
                        chooser.getSelectedFile().getName());

                // last directory saved


                try {
                    Image img = ImageReadWrite.read(chooser.getSelectedFile());
                    ImageFrame iFrame = new ImageFrame(img);
                    deskPane.add(iFrame);
                    iFrame.setVisible(true);

                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                File file = chooser.getSelectedFile();
                  File directory = file.getParentFile();
                  
                                    
                  try {
                      FileOutputStream fos = new FileOutputStream("LastCall.tmp");
                      ObjectOutputStream oos = new ObjectOutputStream(fos);

                       oos.writeObject(directory);
                       oos.close();
                    }
                    catch(IOException e) {
                    }
                    
                                        //***** I am duplicating a local variable here so I assume its just
                                        //***** setting the directory to null?
                    File directory = null;     // init to null
                
                    try {
                        FileInputStream fis = new FileInputStream("LastCall.tmp");
                        ObjectInputStream ois = new ObjectInputStream(fis);
                         directory = (File) ois.readObject();
                           ois.close();
                        }
                        catch (Exception e) {    // OK no file or cast error <------- Exception instead of //IOException
                        }
                    
                                        //*********** Does this really need to be here?  I already have a JFileChooser right
                                        //***** where I start this class; so it's also a duplicate local variable
                        JFileChooser chooser;
                    if(directory = null)
                       chooser = new JFileChooser();                     // first call
                    else
                       chooser = new JFileChooser(directory);        // last directory saved
                    
                    
            }            
        }            
    }



Thanks again!!!!
User is offlineProfile CardPM

Go to the top of the page

pbl
post 2 Jul, 2008 - 08:21 PM
Post #6


D.I.C Lover

Group Icon
Joined: 6 Mar, 2008
Posts: 1,883



Thanked 111 times

Dream Kudos: 75
My Contributions


CODE

    File directory = null;     // init to null
                
    try {
        FileInputStream fis = new FileInputStream("LastCall.tmp");
        ObjectInputStream ois = new ObjectInputStream(fis);
        directory = (File) ois.readObject();
        ois.close();
        }
    catch (Exception e) {    // OK no file or cast error <------- Exception instead of //IOException
    }

You need to initialize directory to null.
That way you tell the Java compiler "I know what I am doing"
As the try block might fail opening the FileInputStream nothing garantees that directory will be initialized so the Java compiler will issue an error "directory might not be initialized"

And you are right you don't need to declare another JFileChooser, you can use the existing one

But I don't understand that:

CODE

     JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter(
                    "JPG, GIF, & PNG Images", "jpg", "gif", "png");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(parent);
            if(returnVal == JFileChooser.APPROVE_OPTION) {


You should try to open the file before doing that to get what was the directory of the last session....
If you always start from fresh every time what it the use of the file ?
If you just want to remember it from the last time you clicked the button (or whatever fires your actionPerformed() no need to save the directory in a file, just keep it in an instance variable "directory"
I though you wanted to remember the last directory accessed from session to session...
User is offlineProfile CardPM

Go to the top of the page

Fast ReplyReply to this topicStart new topic
Time is now: 8/29/08 06:25PM

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month