In this tutorial we will learn how to access resources (file/web resources).
Spring provides an unified resource access mechanism via interface ResourceLoader .
ResourceLoader is a super interface of ApplicationContext. We can access resources using application context instance or we can inject ResourceLoader as a bean or we can even use it outside of Spring container.
Definition of ResourceLoader(Version: spring-framework 6.1.2) package org.springframework.core.io;
........
public interface ResourceLoader {
.............
Resource getResource(String location); 1
.............
ClassLoader getClassLoader(); 2
}
The Resource interface
It is a resource descriptor that abstracts from the actual type of underlying resource, such as a file or class path resource.
Definition of Resource(Version: spring-framework 6.1.2) package org.springframework.core.io;
........
public interface Resource extends InputStreamSource {
boolean exists();
boolean isReadable();
boolean isOpen();
boolean isFile();
URL getURL() throws IOException;
URI getURI() throws IOException;
File getFile() throws IOException;
ReadableByteChannel readableChannel() throws IOException;
byte[] getContentAsByteArray() throws IOException;
String getContentAsString(Charset charset) throws IOException;
long contentLength() throws IOException;
long lastModified() throws IOException;
Resource createRelative(String relativePath) throws IOException;
.............
String getFilename();
String getDescription();
}
Resource interface extends InputStreamSource which has a method to get an instance of java.io.InputStream to read the resource data.
Definition of InputStreamSource(Version: spring-framework 6.1.2) package org.springframework.core.io;
........
public interface InputStreamSource {
InputStream getInputStream() throws IOException;
}
Implementations of Resource
There are multiple implementations of Resource interface: FileSystemResource , ClassPathResource , UrlResource . The good thing is, we don't have to know about those implementations as our prefix based resource location triggers and initializes related implementation.
Example
In this example we will see how to use ResourceLoader and Resource outside of Spring context.
A test resource file
src/main/resources/myFile.txtthis is a my file content.
Loading via classpath
package com.logicbig.example;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import java.io.IOException;
import java.nio.file.Files;
public class ClasspathFileLoadingExample {
public static void main(String[] args) throws IOException {
ResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = resourceLoader.getResource("classpath:myFile.txt");
byte[] bytes = Files.readAllBytes(resource.getFile().toPath());
String fileContent = new String(bytes);
System.out.println(fileContent);
}
}
Outputthis is a my file content.
Loading via absolute path
package com.logicbig.example;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import java.io.IOException;
import java.nio.file.Files;
public class FileUrlLoadingExample {
public static void main(String[] args) throws IOException {
ResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = resourceLoader.getResource("file:D:/test/myTestFile.txt");
byte[] bytes = Files.readAllBytes(resource.getFile().toPath());
String fileContent = new String(bytes);
System.out.println(fileContent);
}
}
Outputtest file content
Loading a web resource
package com.logicbig.example;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class HttpUrlLoading {
public static void main(String[] args) throws IOException {
ResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = resourceLoader.getResource("url:http://www.example.com");
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(resource.getInputStream()))) {
reader.lines().forEach(stringBuilder::append);
}
System.out.println(stringBuilder.toString());
}
}
Output<!doctype html><html><head> <title>Example Domain</title> <meta charset="utf-8" /> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style type="text/css"> body { background-color: #f0f0f2; margin: 0; padding: 0; font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; } div { width: 600px; margin: 5em auto; padding: 2em; background-color: #fdfdff; border-radius: 0.5em; box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02); } a:link, a:visited { color: #38488f; text-decoration: none; } @media (max-width: 700px) { div { margin: 0 auto; width: auto; } } </style> </head><body><div> <h1>Example Domain</h1> <p>This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.</p> <p><a href="https://www.iana.org/domains/example">More information...</a></p></div></body></html>
In next tutorials we will see how to autowire ResourceLoader and Resource in Spring beans.
Example ProjectDependencies and Technologies Used: - spring-context 6.1.2 (Spring Context)
Version Compatibility: 3.2.3.RELEASE - 6.1.2 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 17
- Maven 3.8.1
|