java读取resource目录下文件的方法示例
发布时间:2020-12-14 19:48:48 所属栏目:Java 来源:网络整理
导读:本文主要介绍的是java读取resource目录下文件的方法,比如这是你的src目录的结构 ├── main│ ├── java│ │ └── com│ │ └── test│ │ └── core│ │ ├── bean│ │ ├── Test.java│ └── resources│ └── test│ ├── test.t
本文主要介绍的是java读取resource目录下文件的方法,比如这是你的src目录的结构 ├── main │ ├── java │ │ └── com │ │ └── test │ │ └── core │ │ ├── bean │ │ ├── Test.java │ └── resources │ └── test │ ├── test.txt └── test └── java 我们希望在Test.java中读取test.txt文件中的内容,那么我们可以借助Guava库的Resource类 示例代码如下 public class TestDemo { public static void main(String args[]) throws InterruptedException,URISyntaxException,IOException { BufferedInputStream bufferedInputStream = (BufferedInputStream) Resources.getResource("test/test.txt").getContent(); byte[] bs = new byte[1024]; while (bufferedInputStream.read(bs) != -1) { System.out.println(new String(bs)); } } } 核心函数就是 public static URL getResource(String resourceName) { ClassLoader loader = MoreObjects.firstNonNull( Thread.currentThread().getContextClassLoader(),Resources.class.getClassLoader()); URL url = loader.getResource(resourceName); checkArgument(url != null,"resource %s not found.",resourceName); return url; } 上述代码的核心逻辑很简单,即通过获取classloader来获取resource文件 如果想引入google的guava库,如果你采用的是maven工程的话,可以在pom.xml中加入下面代码: <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency> 总结 以上就是关于java读取resource目录下文件的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。 您可能感兴趣的文章:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |