How to show File Dialog boxes

Created 01 October 2001 00:00
To show a standard windows dialog box, you need to import the java.awt.FileDialog class, which can be used to display files on your machine in the following way:
  FileDialog dlg = new FileDialog(this, "What file do you want to save?", FileDialog.SAVE);
  dlg.setFile("*.java");		// file extension filter
  dlg.setDirectory(".");		// initial directory;
  String saveFile;
  if((saveFile = d.getFile()) != null) {
Alternatively, if you want to maintain a standard swing look and feel, you can import the javax.swing.JFileChooser class, which can be used in the same way.
  JFileChooser chooser = new JFileChooser(".");
  // 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()); 
    System.out.println("You chose to open this directory: " + chooser.getCurrentDirectory()); 
To save files using the swing set, use the following code:
  JFileChooser saver = new JFileChooser(".");
  int returnVal = saver.showSaveDialog(parent); 
  if (returnVal == JFileChooser.APPROVE_OPTION) {
    File selFile = saver.getSelectedFile();
    if (selFile.exists()) {
      int sel = JOptionPane.showConfirmDialog(parent, "Overwrite file " + 
        selFile.getAbsolutePath() + "?", "File exists",
        JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);
      if (sel == JOptionPane.NO_OPTION) {
        // do NO overwrite action here
    // do save action here