获取resource目录下的文件

Java获取resource目录下文件

工作的时候需要读取resource目录下的文件,在此记录一种不会因打包方式影响的读取方法(直接写路径有可能会因为打jar包或者打war包而失效)。


2021/01/11 更新
如果是在Spring环境中,可以使用org.springframework.core.io.ClassPathResource,路径就是resource的路径
注意!!!打成jar包只能只能读取流,不能getFile!!!
并且,在打成jar包时,使用ClassPathResource的getFile或者getPath之类的方式是不能获得结果的,但是可以使用classPathResource.getInputStream直接读取到(有点奇怪)


文件放在db2convert

String jsonPath = "";
// 文件不存在时,resource为null
URL resource = this.getClass().getClassLoader().getResource("db2convert/" + FILE_NAME);
jsonPath = URLDecoder.decode(resource.getPath(),"UTF-8");

// 如果运行在windows上,获取到的path会变成"/E:/Convert...",直接使用的话会报错(会提示:the char ':' is illegal),需要处理一下
Path path = Paths.get(jsonPath.contains(":") ? jsonPath.substring(1) : jsonPath);

然而我并没有在Linux上测试

需要注意的是class.getClassLoader().getResource()class.getResource()这里使用的是类加载器的getResource()方法。
具体的区别就是:
class.getClassLoader().getResource()直接从resources目录下找,用的是相对路径,文件名(参数)前面不用加/
class.getResource()是以resources为根目录的绝对路径,文件名(参数)前面需要加/

posted @ 2020-09-30 15:40  code-blog  阅读(6042)  评论(0编辑  收藏  举报