如何获取Resources目录下的文件

如何获取Resources目录下的文件

方式一

1
2
3
4
5
6
public void function(String fileName) throws IOException {
String path = this.getClass().getClassLoader().getResource(fileName).getPath();
System.out.println(path);
String filePath = URLDecoder.decode(path, "UTF-8");//如果路径中带有中文会被URLEncoder,因此这里需要解码
System.out.println(filePath);
}

方式二

1
2
3
public void function(String fileName) throws IOException {
InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);
}

方式三

1
2
3
public void function5(String fileName) throws IOException {
InputStream in = this.getClass().getResourceAsStream(fileName);
}

方式四

这种方式要在SpringBoot环境下

1
2
3
public void function6(String fileName) throws IOException {
InputStream inputStream = new ClassPathResource(fileName).getInputStream();
}
给作者买杯咖啡吧~~~