我正在编写一个应用程序,我使用XPath来解析xml文件。在我调用DocumentBuilder的解析方法之前,我从文件名创建一个File,并检查文件是否存在。此检查返回true,但是当我尝试解析文件时,我得到了一个带有此stacktrace的nullpointerexception:
Exception in thread "main" java.lang.NullPointerException
at java.io.WinNTFileSystem.normalize(Unknown Source)
at java.io.WinNTFileSystem.getUserPath(Unknown Source)
at java.io.WinNTFileSystem.resolve(Unknown Source)
at java.io.File.getAbsolutePath(Unknown Source)
at java.io.File.getAbsoluteFile(Unknown Source)
at java.io.File.toURI(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at FileHandler.parseFile(OriginatorHandler.java:112)
at Main.main(Main.java:58)
该文件与运行.jar应用程序位于同一文件夹中,并且具有正确的内容。这是我的代码:
public Map<String, List<String>> parseFile(String fileName) {
File file = new File(fileName);
if (!file.exists()) {
System.out.println("Couldn't find file [" + fileName + "]");
System.exit(-1);
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
Document document = null;
try {
builder = factory.newDocumentBuilder();
//This is where the exception is thrown
document = builder.parse(file);
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
return getCaGroups(document, xPath);
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
这个错误会出现什么?该文件存在,它不是null并且位于我运行.jar文件的文件夹中。还有什么可能导致这个问题?
答案 0 :(得分:-1)
请将权限放在AndroidManifest.xml中
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
100%你成功地在工作。