Example of a method for java to read files in the resource directory
- 2020-06-15 08:32:53
- OfStack
This article focuses on how java reads files in the resource directory, such as the structure of your src directory
├ ─ ─ main
│ ├ ─ ─ java
│ │ └ ─ ─ com
│ │ └ ─ ─ test
│ │ └ ─ ─ core
│ │ ├ ─ ─ bean
│ │ ├ ─ ─ Test.java
│ └ ─ ─ resources
│ └ ─ ─ test
│ ├ ─ ─ test.txt
└ ─ ─ test
└ ─ ─ java
We want to read the contents of the test.txt file in Test.java, so we can use the Resource class of the Guava library
The sample code is as follows
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));
}
}
}
The core function is
Resources.getResource
, the function actually encapsulates the following code:
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;
}
The core logic of the above code is simple: get the resource file by getting classloader
If you want to introduce the guava library of google, if you are using the maven project, you can add the following code to pom.xml:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
conclusion
The above is all about java reading files in resource directory. I hope the content of this article can bring you certain help in your study or work. If you have any questions, you can leave a message to communicate.