classpath类路径是什么

Spring Boot

一、简介

classpath类路径在 Spring Boot 中既指程序在打包前的/java/目录加上/resource目录,也指程序在打包后生成的/classes/目录。两者实际上指的是同一个目录,里面包含的文件内容一模一样。


二、获取classpath路径

以下两种方式均可,但是并不能用于生产环境,因为当我们把程序打成jar包时,由于jar包本质是压缩文件,无法被直接打包,所以生成的路径中会含有感叹号!导致路径定位错误,例如:jar!/BOOT-INF/classes!/application.yml (No such file or directory)

// 方式一:
String path1 = ClassUtils.getDefaultClassLoader().getResource("").getPath();

// 方式二:
String path2 = ResourceUtils.getURL("classpath:").getPath();

此时,如果我们想要读取jar包内的文件,可以采取第 3 种方式不读取路径、直接读取文件流:

// 方式 三
InputStream input = ClassUtils
        .getDefaultClassLoader()
        .getResourceAsStream("application.yml");
Reader reader = new InputStreamReader(input, "UTF-8");

三、获取项目路径

上面介绍了如何获取classpath路径之后,其实有时候我们会发现自己只想获取当前程序所在路径或jar包所在路径,那么此时又应该如何获取呢?

// 方式一:
File file = new File(".");
File path1 = file.getAbsoluteFile();

// 方式二:
String path2 = System.getProperty("user.dir");

两者方式并无优劣之分,具体使用哪种取决于你的爱好~

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>