java中Class.getResource用法,以及获取文件绝对路径的坑

资料项目中获取资源文件路径方法有

1、xxx.class.getClassLoader().getResource(“”).getPath(); 
获取src资源文件编译后的路径(即classes路径)

2、xxx.class.getClassLoader().getResource(“文件”).getPath(); 
获取classes路径下“文件”的路径

3、xxx.class.getResource(“”).getPath(); 缺少类加载器,获取xxx类经编译后的xxx.class路径

4、this.getClass().getClassLoader().getResource(“”).getPath();

5、
File file = new File("");
String path = file.getAbsolutePath();

处理"file://"前缀

在windows或者Linux获取配置文件如:.properties文件时
使用Class.getResource或者ClassLoader.getResource获取绝对路径classpath时返回的值如下不同

String basepath=Thread.currentThread().getContextClassLoader().getResource("").toString();

Windows输出

basepath=file:/D:/Workspaces/edu.bizoss.com/WebRoot/WEB-INF/classes/

Linux输出

basepath=file:/Workspaces/edu.bizoss.com/WebRoot/WEB-INF/classes/

因此获取绝对路径的截取的也就不同

if(System.getProperty("file.separator").equals("\\")){
    
    
return basepath.substring(6,basepath.length());
}else{
    
    
return basepath.substring(5,basepath.length());
}

参考资料:
1、https://www.cnblogs.com/keyi/p/6282838.html 20210420
2、https://blog.csdn.net/huangchunxia_1/article/details/79231080 20210420
3、https://www.cnblogs.com/linwenbin/p/12580572.html 20210420
4、https://ask.csdn.net/questions/730891 20210420
5、https://blog.csdn.net/yjw_2019/article/details/91794477?utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control&dist_request_id=1331996.8518.16188876251072647&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control 20210420
6、https://blog.csdn.net/JYplute/article/details/107682820 20210420

猜你喜欢

转载自blog.csdn.net/JohinieLi/article/details/115915104