Close

Spring Framework - org.springframework.core.io.ResourceLoader Examples

Spring Framework 

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);
}
}
Original Post




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);
}
}
Original Post




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());
}
}
Original Post




import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

@Component
public class ClientBean {
@Autowired
private ResourceLoader resourceLoader;

@PostConstruct
public void init() throws IOException {
Resource resource = resourceLoader.getResource("classpath:myFile.txt");
File file = resource.getFile();
String s = new String(Files.readAllBytes(file.toPath()));
System.out.println(s);
}
}
Original Post




See Also