使用 ClassLoader getResource() 和 getResourceAsStream()
Class 和 ClassLoader 类中的方法提供了一种与位置无关的方式来定位资源。
我们可以使用ClassLoader
引用从应用程序的resources
包中读取文件。
getResource()
方法返回资源的 URL。
如果资源不存在或者出于安全考虑不可见,则这些方法返回 null
。
getResource()
和 getResourceAsStream()
方法查找具有给定名称的资源。
如果没有找到具有指定名称的资源,则返回 null
。
getResourceAsStream()
返回资源的InputStream
。getResource()
返回资源的 URL。
示例: Java 程序使用 getResource() 方法从资源文件夹中读取文件
package com.onitroad.demo; import java.io.File; import java.io.IOException; import java.nio.file.Files; public class ReadResourceFileDemo { public static void main(String[] args) throws IOException { String fileName = "config/sample.txt"; ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource(fileName).getFile()); // 文件是否存在 System.out.println("File Found : " + file.exists()); // 读取文件内容 String content = new String(Files.readAllBytes(file.toPath())); System.out.println(content); } }
示例: Java 程序使用 getResourceAsStream() 方法从资源文件夹中读取文件
package com.onitroad.demo; import java.io.File; import java.io.IOException; import java.nio.file.Files; import org.apache.commons.io.IOUtils; public class ReadResourceFileDemo { public static void main(String[] args) throws IOException { String fileName = "config/sample.txt"; ClassLoader classLoader = getClass().getClassLoader(); try (InputStream inputStream = classLoader.getResourceAsStream(fileName)) { String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8); System.out.println(result); } catch (IOException e) { e.printStackTrace(); } } }
欢迎 on
it
road
使用ResourceUtils.getFile()
如果应用程序恰好是 Spring WebMVC 或者 Spring Boot 应用程序,那么我们可以直接利用 ResourceUtils
类。
示例: Java 程序使用 ResourceUtils 从资源文件夹中读取文件
File file = ResourceUtils.getFile("classpath:config/sample.txt") // 检查文件是否存在 System.out.println("File Found : " + file.exists()); // 读取文件内容 String content = new String(Files.readAllBytes(file.toPath())); System.out.println(content);
日期:2020-09-17 00:09:35 来源:oir作者:oir