簡體   English   中英

在Java Swing中保存文件時檢查文件是否存在

[英]Checking if file exists when saving file in Java Swing

所以,我在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();
        }
    }
}

Java變量名以小寫字母開頭。 如果我理解你的問題,那么你可以使用File.exists()

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;
    } 
}
boolean fileExists = new File("file.xml").exists();

測試此抽象路徑名表示的文件或目錄是否存在。

返回:當且僅當此抽象路徑名表示的文件或目錄存在時返回 true ; 否則是false

始終先檢查javadoc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM