【发布时间】:2012-04-25 22:29:23
【问题描述】:
我正在开发一个桌面应用程序,它使用 XPath 读取特定的 XML 元素并将它们显示在 JFrame 的文本字段中。
到目前为止,程序运行顺利,直到我决定在File 类中传递一个String 变量。
public void openNewFile(String filePath) {
//file path C:\\Documents and Settings\\tanzim.hasan\\my documents\\xcbl.XML
//is passed as a string from another class.
String aPath = filePath;
//Path is printed on screen before entering the try & catch.
System.out.println("File Path Before Try & Catch: "+filePath);
try {
//The following statement works if the file path is manually written.
// File xmlFile = new File ("C:\\Documents and Settings\\tanzim.hasan\\my documents\\xcbl.XML");
//The following statement prints the actual path
File xmlFile = new File(aPath);
System.out.println("file =" + xmlFile);
//From here the document does not print the expected results.
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
XPath srcPath = XPathFactory.newInstance().newXPath();
XPathShipToAddress shipToPath = new XPathShipToAddress(srcPath, doc);
XPathBuyerPartyAddress buyerPartyPath = new XPathBuyerPartyAddress(srcPath, doc);
} catch (Exception e) {
//
}
}
如果我使用静态路径(即手动编写)定义 xmlFile,则程序按预期工作。但是,如果我将路径作为字符串变量 aPath 传递,而不是编写静态路径,它不会打印预期的结果。
我做了一些谷歌搜索,但没有找到任何具体的东西。
【问题讨论】:
-
aPath变量的值是多少?您希望它打印什么以及它打印什么。没有静态和动态字符串。字符串是字符串。重要的是字符串包含哪些字符。 -
@JBNizet value of aPath = 'C:\\Documents and Settings\\tanzim.hasan\\my documents\\xcbl.XML' 在另一个类中捕获使用 file.getAbsolutePath();然后使用 'path.replaceAll()' 添加反斜杠转义字符。我期望 Document doc = docBuilder.parse(xmlFile); 接收有效的文件路径,以便可以使用 DocumentBuilderFactory 解析文件。但是,它只有在我手动输入路径时才有效 - File xmlFile = new File ("C:\\Documents and Settings\\tanzim.hasan\\my documents\\xcbl.XML");
-
@All - 我发现了一个可能的错误,该错误仅在我手动输入文件路径时才有效。 Document doc = docBuilder.parse(xmlFile); 如果 xmlFile 被替换为它工作的实际文件路径。但是,当它从 xmlFile 更改为 aPath 时再次失败。仅供参考,失败不会发出任何错误消息,它只是在预期数据的地方显示一个空屏幕。
-
字符串中不应该有双反斜杠。您只需要在 String literal 中使用它们,因为必须转义反斜杠,但 String 本身应该只包含单个斜杠。
-
@JBNizet 感谢您的澄清,您所说的很有意义。然而(可悲的是)它仍然没有工作。我删除了前一个类中的 path.replaceAll(),所以现在 String 包含单个斜杠文件路径,而不是 String 文字。此外,我修改了 Document doc = docBuilder.parse(xmlFile); 的行以包含 System.out.println("@DOC "+doc); 输出是- @DOC [#document: null]。有什么想法吗?
标签: java string file new-operator