Java从resources读取文件内容的方法有哪些

发布时间:

本文主要介绍的是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));
  }
 }
}

核心函数就是Resources.getResource,该函数其实封装了下述代码:

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目录下文件的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。