Java程序中读取外部文件时的路径问题

转自:https://www.cnblogs.com/wt20/p/8320346.html

项目经常会读取一些配置文件, 因此getResource方法便能够起到重要作用

使用时主要是两种方法, 一个是字节码文件Class类, 另一个是ClassLoader类加载器

使用Class类时有两种使用方式:

1. 使用"/"  获取到的是classpath路径

2. 不使用"/" 这就是相对路径

ClassLoader类

没有"/"的写法, 获取到的就是classpath路径

测试代码

public class GetResourceTest {

    public static void main(String[] args) {
        System.out.println(GetResourceTest.class.getResource("/test.properties").getPath());
        System.out.println(GetResourceTest.class.getResource("test1.properties").getPath());
        System.out.println(GetResourceTest.class.getClassLoader().getResource("test.properties").getPath());
        System.out.println(GetResourceTest.class.getClassLoader().getResource("/"));
    }

}

结果:

/E:/IdeaJava/studyTest/out/production/studyTest/test.properties
/E:/IdeaJava/studyTest/out/production/studyTest/com/waston/Test/test1.properties
/E:/IdeaJava/studyTest/out/production/studyTest/test.properties
null

工程包结构

以上为https://www.cnblogs.com/wt20/p/8320346.html博主所写

 

最近在做项目时需要对数据库的历史数据进行处理,由于对oracle数据库的定时任务不熟悉所以使用Java编写了一个定时任务

在程序中需要读取一个ctl文件,但是,如果给定目录的话,给客户运行时可能由于文件放在位置出错而不能读取到文件,尝试使用虚拟路径,没有成功,在网上搜到使用此方法可以获取到目录,尝试使用,成功。

 

 

 

 

 

 

转载于:https://www.cnblogs.com/qinshou/p/8999204.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值