java读取resource目录下文件的方法示例
本文主要介绍的是java读取resource目录下文件的方法,比如这是你的src目录的结构
├──main │├──java ││└──com ││└──test ││└──core ││├──bean ││├──Test.java │└──resources │└──test │├──test.txt └──test └──java
我们希望在Test.java中读取test.txt文件中的内容,那么我们可以借助Guava库的Resource类
示例代码如下
publicclassTestDemo{
publicstaticvoidmain(Stringargs[])throwsInterruptedException,URISyntaxException,IOException{
BufferedInputStreambufferedInputStream=(BufferedInputStream)Resources.getResource("test/test.txt").getContent();
byte[]bs=newbyte[1024];
while(bufferedInputStream.read(bs)!=-1){
System.out.println(newString(bs));
}
}
}
核心函数就是Resources.getResource,该函数其实封装了下述代码:
publicstaticURLgetResource(StringresourceName){
ClassLoaderloader=MoreObjects.firstNonNull(
Thread.currentThread().getContextClassLoader(),
Resources.class.getClassLoader());
URLurl=loader.getResource(resourceName);
checkArgument(url!=null,"resource%snotfound.",resourceName);
returnurl;
}
上述代码的核心逻辑很简单,即通过获取classloader来获取resource文件
如果想引入google的guava库,如果你采用的是maven工程的话,可以在pom.xml中加入下面代码:
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency>
总结
以上就是关于java读取resource目录下文件的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。