获取resource目录下的文件

Java获取resource目录下文件

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

文件放在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为根目录的绝对路径,文件名(参数)前面需要加/

原文地址:https://www.cnblogs.com/lixin-link/p/13731773.html