我在android中使用dom解析器来解析XML文件。 另外,我使用eclipse。
我做:
File file = new File("myfile.xml");
if(file!= null)
Log.d(MainActivity.LOG_TAG,"FILE OK");
else
Log.d(MainActivity.LOG_TAG,"FILE NOT OK!!!");
在上一个声明之后,我在LogCat中获得了“ FILE OK ”。
然后我想解析“myfile.xml”。系统找不到指定的文件
我的代码如下:
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(file);
Log.d(MainActivity.LOG_TAG," Before parsing");
if(doc != null)
Log.d(MainActivity.LOG_TAG," DOC is not null");
else
Log.d(MainActivity.LOG_TAG," DOC IS NULL!!!");
我进入LogCat:
Before parsing
W/System.err(2099): java.io.FileNotFoundException: /myfile.xml: open failed: ENOENT (No such file or directory)
我注意到在myfile.xml之前有一个'/',我无法理解root的位置 DIR
任何人都可以帮助我吗? 感谢
答案 0 :(得分:3)
从资产文件夹中打开文件:
InputStream inStream = getActivity().getAssets().open("myfile.xml");
从外部存储器(SD):
File toPath = Environment.getExternalStoragePublicDirectory();
File xmlFile = new File(toPath, "myfile.xml");
从应用的本地存储:
FileInputStream inFile = mAppActivity.openFileInput("myfile.xml");
目录和文件的Context类中有许多其他方法。