介绍两种获取资源的方式:
一、通过ClassLoader获取:
loader.getResourceAsStream("a/b/temp.txt");--获取src下/a/b包下的temp.txt资源
二、通过Class获取:
加"/":
与ClassLoader一样。class.getResourceAsStream("/a/b/temp.txt")
不加"/":
class.getResourceAsStream("temp.txt")。表示获取当前类路径下的资源。
举个栗子:
package com.io.test; import java.io.InputStream; public class TestIo { public static void main(String[] args) { //一、通过ClassLoader方式 ClassLoader loader = TestIo.class.getClassLoader();//直接从跟路径搜索 InputStream a1 = loader.getResourceAsStream("a.txt"); InputStream b1 = loader.getResourceAsStream("test/file/b.txt"); InputStream c1 = loader.getResourceAsStream("com/io/test/c.txt"); System.out.println("a1=>"+a1); System.out.println("b1=>"+b1); System.out.println("c1=>"+c1); //二、通过Class方式 Class<TestIo> clazz = TestIo.class; InputStream a2 = clazz.getResourceAsStream("/a.txt");//斜杠表示直接从根路径开始搜索 InputStream a3 = clazz.getResourceAsStream("../../../a.txt");//通过相对路径 InputStream c2 = clazz.getResourceAsStream("c.txt");//当前类路劲,相对路径 InputStream c3 = clazz.getResourceAsStream("/com/io/test/c.txt");//从跟路径开始搜索 System.out.println("a2=>"+a2); System.out.println("a3=>"+a3); System.out.println("c2=>"+c2); System.out.println("c3=>"+c3); } }
a1=>[email protected] b1=>[email protected] c1=>[email protected] a2=>[email protected] a3=>[email protected] c2=>[email protected] c3=>[email protected]
原文地址:https://www.cnblogs.com/zomicc/p/12259483.html
时间: 2024-10-19 16:27:06