天天看点

JAVA Appliation下取得资源文件的路径

今天要写一个单元测试,这个单元测试类要去读和它同目录的一个XML文件。它的位置如下:

ConfigFactoryImplTest要去读取boss-connector-service.xml。

JAVA Appliation下取得资源文件的路径

那么如果得到这个文件呢?先看下面的一个对路径的测试代码

import java.io.File;

public class PathTest {

  public static void main(String[] args) throws Exception {

    System.out.println(

    Thread.currentThread().getContextClassLoader().getResource(""));

    System.out.println(PathTest.class.getClassLoader().getResource(""));

    System.out.println(ClassLoader.getSystemResource(""));

    System.out.println(PathTest.class.getResource(""));

    System.out.println(PathTest.class.getResource("/"));

    System.out.println(new File("").getAbsolutePath());

    System.out.println(System.getProperty("user.dir"));

  }

}

打印各种路径结果如下:

file:/E:/wxxr_projects2/wxxr-applications/wxxr-boss-connector/target/test-classes/

file:/E:/wxxr_projects2/wxxr-applications/wxxr-boss-connector/target/test-classes/com/wxxr/boss/config/

E:\wxxr_projects2\wxxr-applications\wxxr-boss-connector

发现PathTest.class.getResource("")得到了绝对路径,嗯,就它了。于是将ConfigFactoryImplTest类里的代码书写如下(这里是用DOM来读XML):

    private static Element getRootElement() throws Exception {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        DocumentBuilder db = dbf.newDocumentBuilder();

        Document doc = db.parse(ConfigFactoryImplTest.class.getResource("") + "boss-connector-service.xml");

        return doc.getDocumentElement();

    }

后记:

得到资源文件的路径,在不同的环境(如:Eclipse RCP、Tomcat、Weblogic、简单的Java Application),方法都是略有不同的。具体的环境要具体分析。