看到有小伙伴提问java打包成jar包访问文件的绝对路径报错问题。
这里给出一个解决方案:
解释:打包成jar包后,直接访问文件绝对路径是找不到文件的,会抛出FileNotFoundException。
必须以IO流的方式访问文件。接下来看例子,直接上代码!
public static void main(String[] args) {
Properties prop = new Properties();
try {
// File file = new FileSystemResource("src/main/resources/domian.properties").getFile();
prop.load(new ClassPathResource("/domian.properties").getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
Enumeration<Object> keys = prop.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement().toString();
String value = prop.getProperty(key);
System.out.println(value);
}
}
文件位置:
如果有编码问题,使用这段代码设置编码
Properties prop = new Properties();
try {
// File file = new FileSystemResource("src/main/resources/domian.properties").getFile();
prop.load(new InputStreamReader(new ClassPathResource("/prop.properties").getInputStream(), "GBK"));
} catch (IOException e) {
e.printStackTrace();
}
其中的ClassPathResource类需要导入jar包:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>