Re: JFileChooser and existing files

From: Allan Bruce (
Date: 01/12/04

Date: Mon, 12 Jan 2004 18:38:17 -0000

"Andrew Thompson" <> wrote in message
> "Allan Bruce" <> wrote in message
> news:btu1ve$b1r$
> | I am using a JFileChooser to select a file which I wish to save
> a String to.
> | This works fine however if the file already exists, my program
> just writes
> | over the file without any warning. Is there an option for the
> JFileChooser
> | to ask if the user wishes to replace the existing file, just
> like a Windows
> | FileChooser?
> I am pretty sure the Windows file chooser
> does _not_ do any such checking. It is
> really up to the programmer to check..
> if file.exists()
> {
> if ( JOptionPane.showConfirmDialog("Are you
> sure?")==JOptionPane.YES_OPTION )
> (..... write the file)
> }

I created my own class that extends the JFileChooser and over-rides the
approveSelection(). This makes it feel much more like the Windows
FileChooser, as it provides the dialog within the FileChooser itself. (By
the Windows FileChooser, I mean the Win32 one which I have used extensively
from C/C++).
I am new to Java, if my code below has a problem, could you please let me

private class MyFileChooser extends JFileChooser
        public MyFileChooser()

        public MyFileChooser(String baseDir)

        public void approveSelection()
                //show some error message
                return;//the FileChooser wont close until and unless u call

   private boolean validateFile(File file)
            //do your validation here
            if (file.exists())
                if (JOptionPane.showConfirmDialog(null, "File exists,
overwrite?", "Overwrite File?", JOptionPane.YES_NO_OPTION) ==
                    return true;
                return false;
  return true;