获取类路径下文件的绝对路径

时间:2021-07-05 18:39:57   收藏:0   阅读:0

获取类路径下文件的绝对路径

在IDEA软件中,src是类的根路径。

技术图片

package com.happy.reflection;

public class AboutPath {
    public static void main(String[] args) {
        String path = Thread.currentThread().getContextClassLoader().getResource("test.properties").getPath();

        System.out.println(path);
    }
}

运行结果:

技术图片

如果test.properties在com文件夹下,

技术图片

则修改相应代码为:

String path = Thread.currentThread().getContextClassLoader().getResource("com/test.properties").getPath();

读取test.properties里面的内容

技术图片

package com.happy.reflection;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Properties;

public class AboutPath {
    public static void main(String[] args) throws Exception {
        String path = Thread.currentThread().getContextClassLoader().getResource("test.properties").getPath();

        FileReader reader = new FileReader(path);
        Properties pro = new Properties();
        pro.load(reader);
        reader.close();
        //通过key获取value
        String message = pro.getProperty("importantMessage");
        System.out.println(message);
    }
}

运行结果:

技术图片

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!