Java中通用的文件路径【不受操作系统影响!】

1、通用方式获取文件绝对路径

String path = Thread.currentThread().getContextClassLoader().getResource("类路径下的文件地址").getPath();

注: 这个文件必须在类路径下。

2、什么是类路径下?

在src下的都是类路径下
src是类的根路径

3、解释

方法备注
Thread.currentThread()当前线程对象。
getContextClassLoader()是线程对象的方法,可以获取到当前线程的类加载器对象。
getResource()【获取资源】这是类加载器对象的方法,当前线程的类加载器默认从类的根路径下加载资源。
getPath()获取文件绝对路径

eg.

/*
研究一下文件路径的问题。
怎么获取一个文件的绝对路径。以下讲解的这种方式是通用的。但前提是:文件需要在类路径下。才能用这种方式。
 */
class AboutPath{
    public static void main(String[] args) throws FileNotFoundException {
        // 这种方式的路径缺点是:移植性差,在IDEA中默认的当前路径是project的根。
        // 这个代码假设离开了IDEA,换到了其它位置,可能当前路径就不是project的根了,这时这个路径就无效了。
        File reader = new File("Practice/src/reflectClassInfo2.properties");
        System.out.println(reader.exists() + " " + reader.getPath());

        // 接下来说一种比较通用的一种路径。即使代码换位置了,这样编写仍然是通用的。
        // 注意:使用以下通用方式的前提是:这个文件必须在类路径下。
        String path = Thread.currentThread().getContextClassLoader().getResource("reflectClassInfo2.properties").getPath();
        // 采用以上的代码可以拿到一个文件的绝对路径。
        // /D:/996-CodeSection/001-IDEA/0.JavaSE/TestProject/out/production/practice/reflectClassInfo2.properties
        System.out.println(path);

        String path2 = Thread.currentThread().getContextClassLoader().getResource("javase/reflectBean/db.properties").getPath();
        // /D:/996-CodeSection/001-IDEA/0.JavaSE/TestProject/out/production/practice/javase/reflectBean/db.properties
        System.out.println(path2);
    }
}

5、将获取到的文件以流的形式返回

InputStream reader = Thread.currentThread().getContextClassLoader().getResourceAsStream("类路径下的文件地址");

6、解释

方法备注
Thread.currentThread()当前线程对象。
getContextClassLoader()是线程对象的方法,可以获取到当前线程的类加载器对象。
getResourceAsStream()获取资源并以流的形式返回

eg.

class IoPropertiesTest{
    public static void main(String[] args) throws IOException {
        //以前
        /*String path = Thread.currentThread().getContextClassLoader().getResource("reflectClassInfo2.properties").getPath();
        FileReader reader = new FileReader(path);*/

        //现在
        // 直接以流的形式返回。
        InputStream reader = Thread.currentThread().getContextClassLoader().getResourceAsStream("reflectClassInfo2.properties");
        Properties pro = new Properties();
        pro.load(reader);
        reader.close();
        // 通过key获取value
        String className = pro.getProperty("className");
        System.out.println(className);//java.util.Date
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值