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
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44715943/article/details/120594882
今日推荐