package com.xinwei.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesLoader {
public static void main(String[] args) {
// test1();
test2();
}
//在使用Class.getResourceAsStream 时, 资源路径有两种方式, 一种以 / 开头,则这样的路径是指定绝对路径,
// 如果不以 / 开头, 则路径是相对与这个class所在的包的。
private static void test2() {
InputStream in = PropertiesLoader.class.getResourceAsStream("/register.properties");
Properties prop = new Properties();
try {
prop.load(in);
String roleId = prop.getProperty("request.roleIds");
System.out.println(roleId);
} catch (IOException e) {
e.printStackTrace();
}
}
//在使用ClassLoader.getResourceAsStream时, 路径直接使用相对于classpath的绝对路径
private static void test1() {
InputStream in =PropertiesLoader.class.getClassLoader().getResourceAsStream("register.properties");
Properties prop = new Properties();
try {
prop.load(in);
String roleId = prop.getProperty("request.roleIds");
System.out.println(roleId);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//举例,下面的三个语句,实际结果是一样的:
//com.explorers.Test.class.getResourceAsStream("abc.jpg")
//= com.explorers.Test.class.getResourceAsStream("/com/explorers/abc.jpg")
//= ClassLoader.getResourceAsStream("com/explorers/abc.jpg")