-3

What I tried to do is to see if a file with the same name already exist in the folder. I have tried to use the method file.exists, but it only says if a file exists in the folder.

if (option == JFileChooser.APPROVE_OPTION) {
    file = new File(fileChooser.getSelectedFile().toString() + ".html");

    try {
        FileWriter writer = new FileWriter(file);
        if (file.exists()) {
            int ergebnis = JOptionPane.showConfirmDialog(TiltungsplanGUI.this,
                    "The File exists already. Overwrite?", "Meldung",
                    JOptionPane.YES_NO_OPTION);
            if (ergebnis == JOptionPane.YES_OPTION) {
                writer.write(r.getTilgungsplan());
            }
        }

        writer.close();

    } catch (IOException e1) {
        // TODO Auto-generated catch block
        JOptionPane.showMessageDialog(TiltungsplanGUI.this, e1.getMessage());
    } catch (RatenRechnerException e1) {
        // TODO Auto-generated catch block
        JOptionPane.showMessageDialog(TiltungsplanGUI.this, e1.getMessage());
    }

}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Chris 344
  • 1
  • 2

1 Answers1

2
new FileWriter(file)

creates the file. It's nonsensical to check whether it exists after you have just created it.

You may want to move the check before the creation of the FileWriter ...

meriton
  • 68,356
  • 14
  • 108
  • 175
  • 1
    What about race condition? – Orace Nov 05 '21 at 16:05
  • 1
    Good point. If races are possible, I'd use `Files.newBufferedWriter(path, charset, StandardOpenOption.CREATE_NEW)` to create the file only if it doesn't exist yet. – meriton Nov 05 '21 at 16:16