Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JFileChooser and checking for overwrite

Tags:

java

swing

I am using a JFileChooser in my Java app and I need to ask the user if they wish to overwrite the file if the selected file already exist?

Is there a provided functionality that I can use? Or roll my own? I am using Swing and JDK 1.4

like image 938
reza Avatar asked Jan 18 '23 00:01

reza


1 Answers

The default one doesn't have that functionality, you'll have to write your own. Or use someone else's.

private class CustomFileChooser extends JFileChooser {
  private String extension;
  public CustomFileChooser(String extension) {
    super();
    this.extension = extension;
    addChoosableFileFilter(new FileNameExtensionFilter(
      String.format("%1$s Images (*.%1$s)", extension), extension));
  }

  @Override public File getSelectedFile() {
    File selectedFile = super.getSelectedFile();

    if (selectedFile != null) {
      String name = selectedFile.getName();
      if (!name.contains("."))
        selectedFile = new File(selectedFile.getParentFile(), 
          name + '.' + extension);
    }

    return selectedFile;
  }

  @Override public void approveSelection() {
    if (getDialogType() == SAVE_DIALOG) {
      File selectedFile = getSelectedFile();
      if ((selectedFile != null) && selectedFile.exists()) {
        int response = JOptionPane.showConfirmDialog(this,
          "The file " + selectedFile.getName() + 
          " already exists. Do you want to replace the existing file?",
          "Ovewrite file", JOptionPane.YES_NO_OPTION,
          JOptionPane.WARNING_MESSAGE);
        if (response != JOptionPane.YES_OPTION)
          return;
      }
    }

    super.approveSelection();
  }
}
like image 160
tskuzzy Avatar answered Jan 29 '23 16:01

tskuzzy