另一天,SAX,Java和朋友發生了另一個奇怪的錯誤。SAX解析器不能解析文件名
我需要迭代一個File
對象列表並將它們傳遞給SAX解析器。但是,解析器由於IOException
而失敗。但是,各種各樣的File
對象方法確認文件確實存在。
這是我得到的輸出:
11:53:57.838 [MainThread] DEBUG DefaultReactionFinder - C:\project\trunk\application\config\reactions\TestReactions.xml
11:53:57.841 [MainThread] ERROR DefaultReactionFinder - C:\project\trunk\application\config\reactions\null (The system cannot find the file specified)
所以問題顯然是在第二行null
。我試過幾乎所有的文件作爲參數傳遞給解析器,包括作爲String
(都來自getAbsolutePath()
和手動輸入),作爲URI
,更奇怪的是,作爲FileInputStream
(爲此我得到了相同的錯誤,除了整個相對路徑被報告爲空,所以C:\project\trunk\null
)。
我所能想到的是SAXParserFactory
配置不正確。不過,我不知道什麼是錯的。
這裏是有關的代碼:
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
try {
parser = factory.newSAXParser();
}
catch (ParserConfigurationException e) {
throw new InstantiationException("Error configuring an XML parser. Given error message: \"" + e.getMessage() + "\".");
}
catch (SAXException e) {
throw new InstantiationException("Error creating a SAX parser. Given error message: \"" + e.getMessage() + "\".");
}
...
for (File f : fileLister.getFileList()) {
logger.debug(f.getAbsolutePath());
try {
parser.parse(f, new ReactionHandler(input));
//FileInputStream fs = new FileInputStream(f);
//parser.parse(fs, new ReactionHandler(input));
//fs.close();
}
catch (IOException e) {
logger.error(e.getMessage());
throw new ReactionNotFoundException("An error occurred processing file \"" + f + "\".");
}
...
}
我並沒有特別的規定,提供自定義的SAX解析器實現:我用的是系統默認的。任何幫助將不勝感激!
編輯的更多信息:
我,當我使用流代碼:
FileInputStream fs = new FileInputStream(f);
InputSource is = new InputSource(fs);
//is.setSystemId(f.toURI().toString());
parser.parse(is, new ReactionHandler(input));
其中給出輸出
11:07:10.703 [MainThread] DEBUG DefaultReactionFinder - C:\project\trunk\application\config\reactions\TestReactions.xml
11:07:10.706 [MainThread] ERROR DefaultReactionFinder - C:\project\trunk\application\null (The system cannot find the file specified)
這表明XML文件的相對目錄不是正確解決。如果我包含被註釋掉的行,則相對目錄會再次正確解析。這讓我覺得某個地方某些設置是不正確的...