Java:在新File()中传递String变量;

Tan*_* H. 6 java string file new-operator

我正在开发一个桌面应用程序,它使用XPath读取特定的XML元素并将其显示在文本字段中JFrame.

到目前为止,程序运行顺利,直到我决定StringFile类中传递一个变量.

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) {
        //
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我xmlFile使用静态路径定义(即手动编写),则程序按预期工作.但是,如果我将路径作为字符串变量传递,则不会写入静态路径,aPath而是不会打印预期的结果.

我做了一些谷歌搜索但没有找到任何具体的东西.

Jas*_*ley 1

只需使用内置对象方法:

System.out.println("file = "+xmlFile.toString());
Run Code Online (Sandbox Code Playgroud)

您还可以使用:

System.out.println("f = " + f.getAbsolutePath());
Run Code Online (Sandbox Code Playgroud)

另外,如果您遇到文件不存在的问题,请先检查然后继续:

File file = new File (aPath);
if(file.exists()) {
  //Do your work
}
Run Code Online (Sandbox Code Playgroud)