在Java Swing中保存文件时检查文件是否存在

在Java Swing中保存文件时检查文件是否存在,java,swing,save,Java,Swing,Save,因此,我正在用Java保存XML数据。我允许用户选择路径和名称。现在,如果文件已经存在,我想用一条消息提示他们:“您想覆盖当前文件吗?”我还能这样做吗?谢谢 JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); chooser.setApproveButtonText("Save"); chooser.setDialogTitle("Save");

因此,我正在用Java保存XML数据。我允许用户选择路径和名称。现在,如果文件已经存在,我想用一条消息提示他们:“您想覆盖当前文件吗?”我还能这样做吗?谢谢

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();
        }
    }
}
测试此抽象路径名表示的文件或目录是否存在

返回:
true
当且仅当此抽象路径名表示的文件或目录存在时<代码>错误否则


总是先检查

Java变量名以小写字母开头。如果我理解你的问题,那么是的,你可以使用

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;
    } 
}
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;
    } 
}