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

本文介绍了一种在Java单元测试中读取同目录下XML文件的方法,并通过实例展示了如何使用Class.getResource方法获取正确的文件路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

今天要写一个单元测试,这个单元测试类要去读和它同目录的一个XML 文件。它的位置如下:
ConfigFactoryImplTest
要去读取boss-connector-service.xml



 

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

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/
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/
file:/E:/wxxr_projects2/wxxr-applications/wxxr-boss-connector/target/test-classes/
E:\wxxr_projects2\wxxr-applications\wxxr-boss-connector
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 RCPTomcatWeblogic 、简单的Java Application ),方法都是略有不同的。具体的环境要具体分析。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值