我目前正在编写一个 LibGDX 游戏,我需要为 Sprite 表打开一个 XML 文件。不幸的是,当我尝试打开该文件时,出现了 IOException
。文件存在于正确的位置,项目已清理并保持最新等。
最重要的是:LibGDX 将在同一目录中打开和显示图像文件,实际上将在其自己的 FileHandle
对象中获取 XML 文件(我已经用它记录了大小和它匹配)。然而,当我将文件发送到 SAX 解析器时,出现异常,提示我无法打开该文件。
这是 ClipSprite
类中的问题代码行:
private void parseConfigFile(FileHandle file) throws ParserConfigurationException, SAXException
{
//Use a SAX parser to get the data out of the XML file.
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLConfigHandler handler = new XMLConfigHandler();
//Parse through the document
try
{
parser.parse(file.path(),handler); //IOException here
}
这是我在 LibGDX 主类的 create
方法中选择游戏文件的代码
//This loads a png file
texture = new Texture(Gdx.files.internal("data/graphics/CDE1/CDE1.png"));
texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
TextureRegion region = new TextureRegion(texture, 0, 0, 512, 275);
//Here I load the xml file and it tells me how many bytes it is
Gdx.app.error("File","xml bytes:"+Gdx.files.internal("data/graphics/CDE1/CDE1.xml").length());
//Here I load the same file and it crashes
//Note that it looks in the subdirectory and finds /CDE1.xml properly
animation = new ClipSprite("data/graphics/CDE1");
来自 logcat 的错误:
java.io.IOException: Couldn't open data/graphics/CDE1/CDE1.xml
为什么它能识别文件,但我仍然得到无法打开它的IOException?感谢您的帮助,如有必要,我会提供更多信息。
最佳答案
只是为了将上面的所有评论合并成一个答案,以防其他人遇到这个或类似的问题:
尝试 Gdx.files.local()
加载您的文件,而不是 Gdx.files.internal()
,因为“内部”文件是从(压缩的)APK,可能不像普通文件那样“可见”。 (这在很大程度上取决于您将路径名传递给的代码想要用它做什么。)
对于 libGDX FileHandle file
对象,使用 file.file()
传递文件句柄,而不是 file.path()
到传递一个可能会被误解的字符串。
对于 libGDX FileHandle 文件
,使用 file.read()
将 InputStream
直接传递给消费者(而不是传递字符串或文件句柄并期望他们打开它)。
libGDX“内部”文件映射到 Android AssetManager file , 所以它们可以是 bit wonky在 some cases .具体来说,它们可能被压缩并存储在 .jar
或 .apk
中,并且对传统文件读取功能不可见。
关于Android 无法使用 LibGDX 打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14544809/