I’m writing a game with LibGDX, and I’m trying to save an XML file, but there’s always an exception (java.io.FileNotFoundException: /data/Slugfest/teams/Team1.xml: open failed: ENOENT (No such file or directory)) when saving the file. This code saves the file.
public void save() {
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result;
if (Gdx.app.getType() == ApplicationType.Android) {
result = new StreamResult(new File("/data/Slugfest/teams/" + name + ".xml"));
} else {
result = new StreamResult(new File(name + ".xml"));
}
transformer.transform(source, result);
Gdx.app.log("Slugfest", "File saved.");
} catch (TransformerException tfe) {
Gdx.app.log("Slugfest", tfe.getLocalizedMessage());
}
}
My manifest file includes the WRITE/READ_EXTERNAL_STORAGE permissions, by the way.
You need to create the directory you are trying to save to. You should check to see if it is there, if not, the create it. Something like this:
Here I check to see if there is an SD card, if not, the I save locally, otherwise, I save to the SD. I also check for files, and delete if they are there. You might not need that, but this is a comprehensive algorithm that should do what you need it to. Take what you need.
Hope it helps.