代码示例:
package com.thb;
import java.io.IOException;
import java.io.InputStream;
public class Demo4 {
public static void main(String[] args) throws IOException {
String resource = "com/thb/test.properties";
// 获得ClassLoader
ClassLoader classLoader = new Demo4().getClass().getClassLoader();
System.out.println("ClassLoader: " + classLoader);
// 通过ClassLoader加载文件,转换为输入流
InputStream inputStream = classLoader.getResourceAsStream(resource);
if (inputStream != null) {
// 判断输入流的可读字节数
System.out.println("available bytes: " + inputStream.available());
} else {
System.out.println("inputStream is null");
}
}
}
运行输出: