我有这个购物篮,请看https://i.stack.imgur.com/9ty3E.png
一切正常,但我的文件保存,意味着发生的事情是当你提交保存并且现有项目打开并且它覆盖旧的xml文件但是它完全跳过它并转到else语句。
@FXML
private void handleSaveAs() {
FileChooser fileChooser = new FileChooser();
// Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(
"XML files (*.xml)", "*.xml");
fileChooser.getExtensionFilters().add(extFilter);
// Show save file dialog
File file = fileChooser.showSaveDialog(mainApp.getPrimaryStage());
if (file != null) {
// Make sure it has the correct extension
if (!file.getPath().endsWith(".xml")) {
file = new File(file.getPath() + ".xml");
}
mainApp.saveItemDataToFile(file);
}
}
public File getItemFilePath() {
Preferences prefs = Preferences.userNodeForPackage(MainApp.class);
String filePath = prefs.get("Filepath", null);
if (filePath != null) {
return new File(filePath);
} else {
return null;
}
}
public void setItemFilePath(File file) {
Preferences prefs = Preferences.userNodeForPackage(MainApp.class);
if (file != null) {
prefs.put("filePath", file.getPath());
primaryStage.setTitle("Shopping Basket - " + file.getName());
} else {
prefs.remove("filePath");
primaryStage.setTitle("Shopping Basket");
}
}
public void loadItemDataFromFile(File file) {
try {
JAXBContext context = JAXBContext
.newInstance(BasketListWrapper.class);
Unmarshaller um = context.createUnmarshaller();
BasketListWrapper wrapper = (BasketListWrapper) um.unmarshal(file);
itemData.clear();
itemData.addAll(wrapper.getItems());
setItemFilePath(file);
} catch (Exception e) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("Could not load data");
alert.setContentText("Could not load data from file:\n"
+ file.getPath());
alert.showAndWait();
}
}
public void saveItemDataToFile(File file) {
try {
JAXBContext context = JAXBContext
.newInstance(BasketListWrapper.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
BasketListWrapper wrapper = new BasketListWrapper();
wrapper.setItems(itemData);
m.marshal(wrapper, file);
setItemFilePath(file);
} catch (Exception e) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("Could not load data");
alert.setContentText("Could not load data from file:\n"
+ file.getPath());
alert.showAndWait();
}
}
继承我的保存代码以供参考
await
答案 0 :(得分:0)
在getItemFilePath
方法中,您尝试获取“ F ilepath”首选项:
String filePath = prefs.get("Filepath", null);
但是在setItemFilePath
方法中,您设置了“文件 P ath”首选项:
prefs.put("filePath", file.getPath());
由于首选项键区分大小写,就像任何其他String
一样,因此您始终会获得默认值,即null。