一、IO流+Properties集合
从根路径开始,相对路径
- 这种方式的路径缺点:移植性差,在IDEA中默认的当前路径是project的根。
- 这个代码假设离开了IDEA,到了其他位置,可能当前路径就不是project的根了,这时路径就无效了。
- FileReader fileReader = new FileReader(“cn.edu.mju.reflect.Myclass”);
public class ReflectTest03 {
public static void main(String[] args) throws Exception {
//通过IO流读取classinfo.properties文件
//FileReader reader = new FileReader("src/classinfo.properties"); //从根路径开始,相对路径
FileReader reader = new FileReader("D:\\Data\\java\\src\\classinfo.properties"); //绝对路径
//创建属性类对象Map
Properties pro = new Properties();
//加载
pro.load(reader);
reader.close();
//通过key获取value
String className = pro.getProperty("className");
System.out.println(className);
//通过反射机制实例化对象
//创建的对象不一定是User对象,创建的对象取决于类名
Class c = Class.forName(className);
Object obj = c.newInstance();
System.out.println(obj);
}
}
二、java.util包下提供的资源绑定器(ResourceBundle)
java.util包下提供了一个资源绑定器,便于 获取属性配置文件的内容。
使用以下方式的时候,属性配置文件xxx.properties必须放在类路径下。
资源绑定器,只能 绑定xxx.properties文件。并且这个文 件必须在类路径下。文件扩展名也必须是properties
并且在写路径的时候,路径后面的扩展名不能写
ResourceBundle bundle = ResourceBundle.getBundle(“classinfo”);//src作为起点
ResourceBundle bundle = ResourceBundle.getBundle("main/java/classinfo");
String className = bundle.getString("className");
System.out.println(className);
三、通用的方式(改造方式一)
接下来说一种比较通用的一种通用的路径,即使代码换位置,这样编写仍是通用的。
使用这种通用方式的前提是:这个文件必须在类路径下。
什么是类路径?src下都是类路径下。
src是类的根路径
Thread.currentThread()
:当前线程对象
getContextClassLoader()
:是线程对象的方法,可以获取到当前线程的类加载器对象。
getResource("")
:是类加载器的方法,当前线程的类加载器默认从类的根路径下加载资源。
这种方式获取绝对路径是通用的额,在不同操作系统都可以。
获取绝对路径:
String path = Thread.currentThread().getContextClassLoader().getResource("classinfo.properties").getPath();
//采用以上代码就可以拿到一个文件的绝对路径
System.out.println(path);
//获取db.properties文件的绝对路径(从类的根路径下作为起点开始)
String path2 = Thread.currentThread().getContextClassLoader().getResource("main/java/cn/edu/mju/bean/db.properties").getPath();
System.out.println(path2);
获取绝对路径的流:
//获取绝对路径
//String path = Thread.currentThread().getContextClassLoader().getResource("main/java/classinfo.properties").getPath();
FileReader fileReader = new FileReader(path);
//以流的形式返回
InputStream fileReader = Thread.currentThread().getContextClassLoader().getResourceAsStream("main/java/classinfo.properties");
Properties properties = new Properties();
properties.load(fileReader);
fileReader.close();
//通过key获取value
String classname = properties.getProperty("className");
System.out.println(classname);