所以,我在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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2912 次 |
| 最近记录: |