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

标签 java string file new-operator

我正在开发一个桌面应用程序,它使用 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 传递,而不是编写静态路径,它不会打印预期的结果。

我进行了一些谷歌搜索,但未能找到任何具体内容。

最佳答案

只需使用内置对象方法:

System.out.println("file = "+xmlFile.toString());

您还可以使用:

System.out.println("f = " + f.getAbsolutePath());

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

File file = new File (aPath);
if(file.exists()) {
  //Do your work
}

关于Java:在 new File() 中传递 String 变量;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10142854/

相关文章:

c - 在结构中填充字符指针

ruby - 我在 ruby​​ 1.8 应用程序中使用 ftools,如何使其与 ruby​​ 1.9 兼容

c# - 性能 : Templates in a Database or a File?

java - setOut方法如何改变System类中final的System.out的值

c++ - 如何创建具有预定义值和分配空间的字符串?

java - 如何在 Java 中比较字符串?

java - Android 存储和检索数据

java - @Transactional(propagation = Propagation.SUPPORTS) 没有事务正在进行

java - 向下转型类内部

java - 将嵌套的 JSON 数据转换为 HTML 表