Harry
Harry

Reputation: 782

Checking if file exists when saving file in Java Swing

So, I am saving XML data in Java. I am allowing the user to choose to path and name. Now, if the file already exists, I want to prompt them with a message like: "Do you want to overwrite the current file?" Is there anyway I can do this? Thanks

JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    chooser.setApproveButtonText("Save");
    chooser.setDialogTitle("Save");
    FileFilter filter = new FileNameExtensionFilter("XML File",
            new String[] { "xml" });
    chooser.setFileFilter(filter);
    chooser.addChoosableFileFilter(filter);
    int r = chooser.showOpenDialog(this);
    if (r == JFileChooser.APPROVE_OPTION) {
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(Shapes.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                    Boolean.TRUE);
            File XMLfile = new File(chooser.getSelectedFile().toString()
                    + ".xml");
            jaxbMarshaller.marshal(myShapes, XMLfile);

        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

Upvotes: 2

Views: 4179

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201439

Java variable names start with a lower case letter. If I understand your question then yes you can use File.exists() and something like

File xmlFile = new File(chooser.getSelectedFile().toString()
        + ".xml");
if (xmlFile.exists()) {
    int response = JOptionPane.showConfirmDialog(null, //
            "Do you want to replace the existing file?", //
            "Confirm", JOptionPane.YES_NO_OPTION, //
            JOptionPane.QUESTION_MESSAGE);
    if (response != JOptionPane.YES_OPTION) {
        return;
    } 
}

Upvotes: 5

Mitch Talmadge
Mitch Talmadge

Reputation: 4755

boolean fileExists = new File("file.xml").exists();

Tests whether the file or directory denoted by this abstract pathname exists.

Returns: true if and only if the file or directory denoted by this abstract pathname exists; false otherwise.

Always check the javadocs first!

Upvotes: 3

Related Questions