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); }}
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); }}
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()); }}
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 jakarta.annotation.PostConstruct;import java.io.File;import java.io.IOException;import java.nio.file.Files;@Componentpublic 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); }}