如何使用Java代码获取资源文件呢?
下文笔者讲述使用java代码获取资源文件的方法及示例分享,如下所示
获取资源文件的实现思路 方式1: 使用构造file对象的方式获取资源文件 方式2: 使用ClassLoader获取资源文件例:使用IO类中的File,Path获取文件
import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; public class TestClass { // 例如 idea下存在resources/test文件 public static void main(String[] args) { // 使用File或Path进行获取文件时,主要收到相对路径和绝对路径的影响 String path = "src/main/resources/test"; File file = new File(path); boolean exists = file.exists(); System.out.println(exists); exists = Files.exists(Paths.get(path)); System.out.println(exists); } }
使用ClassLoader获取资源文件
import java.io.File; import java.io.InputStream; import java.net.URL; public class TestClass { // 例如 idea下存在resources/test文件 public static void main(String[] args) { String path = "test"; // 1 Class获取 URL classResource = TestClass.class.getResource("/test"); // URL InputStream classStream = TestClass.class.getResourceAsStream("/test"); // InputStream File classFile = new File(classResource.getPath()); // 2 ClassLoader获取 URL clResource = TestClass.class.getClassLoader().getResource("test"); // URL InputStream clStream = TestClass.class.getClassLoader().getResourceAsStream("test"); // InputStream File clFile = new File(clResource.getPath()); } }
使用ClassLoader相对路径获取时,起始路径为classpath(也约等于resources目录下) 使用class相对路径获取时,起始目录则是当前类的目录 ================================================================================ 如: com.java265.TestClass 使用TestClass.class.getResource("test")时,是获取com/java265/TestClass文件 这则会导致获取resources/test文件失败,而绝对路径则都是从classpath开始。 获取resources目录下的资源文件时 使用当前类.class.getClassLoader().getResourceAsStream()方法 进行获取资源文件
SpringBoot获取资源扩展
SpringBoot 提供工具ResourceUtils.getURL("classpath:test")获取资源文件 当携带classpath:前缀时 使用类加载器获取 其它情况使用URL获取例
public abstract class ResourceUtils { /** Pseudo URL prefix for loading from the class path: "classpath:". */ public static final String CLASSPATH_URL_PREFIX = "classpath:"; // 省略其它代码... public static URL getURL(String resourceLocation) throws FileNotFoundException { Assert.notNull(resourceLocation, "Resource location must not be null"); if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) { // 携带classpath:时进来 String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length()); ClassLoader cl = ClassUtils.getDefaultClassLoader(); URL url = (cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path)); // 使用类加载获取资源文件 if (url == null) { String description = "class path resource [" + path + "]"; throw new FileNotFoundException(description + " cannot be resolved to URL because it does not exist"); } return url; } try { // 其它情况 // try URL return new URL(resourceLocation); } catch (MalformedURLException ex) { // no URL -> treat as file path try { return new File(resourceLocation).toURI().toURL(); } catch (MalformedURLException ex2) { throw new FileNotFoundException("Resource location [" + resourceLocation + "] is neither a URL not a well-formed file path"); } } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。