【问题标题】:Absolute path with XML parser in javajava中带有XML解析器的绝对路径
【发布时间】:2015-04-16 22:05:52
【问题描述】:

我有以下代码来打开一个 XML 文件进行解析。我的问题是变量designPath:它目前必须是我程序根目录的相对路径。但是,当我通过绝对路径时,它不起作用。

// Get the DOM Builder Factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

// Get the DOM Builder
DocumentBuilder builder = factory.newDocumentBuilder();

// Load and Parse the XML document
// document contains the complete XML as a Tree
Document document = builder.parse(ClassLoader.getSystemResourceAsStream(designPath));

如何使用designPath 变量中的绝对路径或相对路径进行这项工作?

问题在于函数ClassLoader.getSystemResourceAsStream 采用“从用于加载类的搜索路径中指定名称的资源”。根据 Java 文档,但我希望能够使用绝对路径。

请注意,我的 designPath 可能与我的程序位于不同的驱动器上。

【问题讨论】:

    标签: java xml file path


    【解决方案1】:

    改为传递InputStream

    // Get the DOM Builder Factory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    
    // Get the DOM Builder
    DocumentBuilder builder = factory.newDocumentBuilder();
    
    // Load and Parse the XML document
    // document contains the complete XML as a Tree
    File file = new File(PATH_TO_FILE);
    InputStream inputStream = new FileInputStream(file);
    
    Document document = builder.parse(inputStream);
    

    或者简单地传递一个新的File对象

    // Get the DOM Builder Factory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    
    // Get the DOM Builder
    DocumentBuilder builder = factory.newDocumentBuilder();
    
    // Load and Parse the XML document
    // document contains the complete XML as a Tree
    Document document = builder.parse(new File(PATH_TO_FILE));
    

    【讨论】:

      【解决方案2】:

      你不能,因为正如你所说,getSystemResourceAsStream 只搜索类路径。

      您可能不得不这样做。

      Document document = null;
      if (ClassLoader.getSystemResource(designPath) != null)
      {
          document = builder.parse(ClassLoader.getSystemResourceAsStream(designPath));
      }
      else
      {
          // use standard file loader
          document = builder.parse(new File(designPath));
      }
      

      如果您希望文件系统上的文件优先,请交换 if 子句。

      【讨论】:

      • 直接传入File 对象与在上述解决方案中传入InputStream 对象有什么区别?有区别吗?
      • 如果您的类路径类似于 CP=/home/user/xmlfiles:program.jar,并且文件路径只是 design.xml,那么您的代码将首先搜索 /home/user/xmlfiles,如果失败,它将查找与您运行它的位置相关的 design.xml。
      • @mohsaied 我认为在您的情况下,传递 InputStream 或 File 对象并不重要,但在其他情况下,您并不总是从文件中获取 InputStream,因此它可能会产生更多感觉传递 InputStream。我会更新我的答案,以便其他人知道有一个选择!
      猜你喜欢
      • 1970-01-01
      • 2018-12-27
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      相关资源
      最近更新 更多