java JavaFX我的文件保存不起作用
我有这个购物篮,看这里https://i.stack.imgur.com/9ty3E.png
除了我的文件保存之外,一切都正常。当你保存文件,打开一个现有的项目,它会覆盖旧的xml文件,但它会完全跳过它,转到else语句
@FXML
private void handleSave() {
File itemFile = mainApp.getItemFilePath();
if (itemFile != null) {
mainApp.saveItemDataToFile(itemFile);
} else {
handleSaveAs();
}
}
这是我的另存为代码供参考
@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();
}
}
# 1 楼答案
在
getItemFilePath
方法中,您试图获得“Filepath”首选项:但是在
setItemFilePath
方法中,您正在设置“filepath”首选项:因为preferences键是区分大小写的,就像任何其他
String
一样,您总是会得到默认值,即null