gpt4 book ai didi

java - Android XML 文件不保存

转载 作者:行者123 更新时间:2023-11-30 04:07:06 25 4
gpt4 key购买 nike

我正在用 LibGDX 编写一个游戏,我正在尝试保存一个 XML 文件,但总是出现异常(java.io.FileNotFoundException:/data/Slugfest/teams/Team1.xml: open failed: ENOENT (没有这样的文件或目录))保存文件时。此代码保存文件。

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());
}
}

顺便说一句,我的 list 文件包含 WRITE/READ_EXTERNAL_STORAGE 权限。

最佳答案

您需要创建要保存到的目录。您应该检查它是否存在,如果不存在,则创建它。像这样:

if (Environment.getExternalStorageState() == null) {
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}

// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}

这里我查看是否有SD卡,如果没有,我就保存到本地,否则,我就保存到SD。我还检查文件,如果有则删除。您可能不需要它,但这是一个综合算法,可以满足您的需要。你要什么就拿。

希望对您有所帮助。

关于java - Android XML 文件不保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11424812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com