Android开发遇java.io.FileNotFoundException:XML反序列化找不到文件
问题分析与解决方案
你遇到的核心问题是在Android应用中错误使用了Windows系统的本地文件路径——Android应用运行在独立的沙盒环境里,完全无法直接访问你电脑本地的C:\Users\Terence\Documents\...这类路径,相对路径也不是指向你电脑的项目目录,而是应用自身的沙盒根目录,这就是为什么所有路径尝试都返回文件不存在。
下面是针对你的需求的几种可行解决方案:
方案1:将XML文件放入assets目录(推荐)
这是存放静态配置资源的常用方式,步骤如下:
- 在你的Android项目中,找到
src/main目录,右键选择New → Folder → Assets Folder,创建assets文件夹(位置默认即可)。 - 把
Test_Single.xml复制到assets目录下。 - 修改代码中的文件读取逻辑,使用
AssetManager来读取文件:
XMLDecoder decoder = null; try { // 获取AssetManager实例 AssetManager assetManager = getAssets(); // 打开assets目录下的XML文件 InputStream inputStream = assetManager.open("Test_Single.xml"); decoder = new XMLDecoder(new BufferedInputStream(inputStream)); equationLib = (EquationLib) decoder.readObject(); myCnt = equationLib.libSets.size(); myEqSetName = equationLib.libSets.get(0).equationSet.name; myTV.setText(String.format("读取成功:%s,共%d个集合", myEqSetName, myCnt)); } catch (Exception e) { e.printStackTrace(); myTV.setText("读取失败:" + e.getMessage()); } finally { if (decoder != null) { decoder.close(); } }
方案2:将XML文件放入res/raw目录
这种方式适合需要通过资源ID访问的静态文件:
- 在
res目录下创建raw文件夹(右键res→New→Directory,命名为raw)。 - 把XML文件复制进去,注意文件名必须全小写、不能有空格或特殊字符,所以建议重命名为
test_single.xml。 - 修改读取逻辑:
XMLDecoder decoder = null; try { // 通过资源ID打开文件 InputStream inputStream = getResources().openRawResource(R.raw.test_single); decoder = new XMLDecoder(new BufferedInputStream(inputStream)); equationLib = (EquationLib) decoder.readObject(); myCnt = equationLib.libSets.size(); myEqSetName = equationLib.libSets.get(0).equationSet.name; myTV.setText(String.format("读取成功:%s,共%d个集合", myEqSetName, myCnt)); } catch (Exception e) { e.printStackTrace(); myTV.setText("读取失败:" + e.getMessage()); } finally { if (decoder != null) { decoder.close(); } }
额外说明
- 你之前写的
File mySearch = new File(myFileStr)判断文件存在的逻辑,在Android里只能用来判断应用沙盒内或外部存储(需权限)的文件,完全无法识别Windows本地路径,所以直接删掉这类针对Windows路径的判断即可。 - 如果你的XML文件需要从外部存储(比如手机的SD卡)读取,还需要申请
READ_EXTERNAL_STORAGE权限(Android 10及以上还需注意分区存储规则),但这种方式不如前两种适合静态配置文件。
内容的提问来源于stack exchange,提问作者T. A. Pfaff
相关产品推荐
相关产品推荐

