优点:
这种获取文件路径的方式移植性高,可以移植到各个系统
前提条件: 文件需要在类路径下(src下的都是类路径),才能用这种方式
src是类的根路径 (在src下开始搜索)
代码演示如下:
import java.io.FileNotFoundException;
public class reflectTest04 {
public static void main(String[] args) throws FileNotFoundException {
/*
解释: 这种获取文件路径的方式移植性高,可以移植到各个系统
Thread.currentThread() 当前线程对象
getContextClassLoader() 是线程对象的方法,可以获取到当前线程的类加载器对象
getResource() 获取资源
getPath() 获取绝对路径
注意:所有的文件都需要从src类的根路径下开始
*/
// Username.properties文件 是在src类的根路径下开始的
String path =Thread.currentThread().getContextClassLoader().getResource("Username.properties").getPath();
System.out.println(path); // /D:/IdeaProjects/javase/out/production/chapter9/Username.properties
// User.properties文件是在包里面呢, 注意我们需要在src根路径开始
String path1 =Thread.currentThread().getContextClassLoader().getResource("bj\\powernode\\javase\\reflect\\User.properties").getPath();
System.out.println(path1);
// /D:/IdeaProjects/javase/out/production/chapter9/bj%5cpowernode%5cjavase%5creflect%5cUser.properties
// 不能这样写
String path2 =Thread.currentThread().getContextClassLoader().getResource("User.properties").getPath();
System.out.println(path2); // 这样写会空指针异常, 因为User.properties文件 不是在src类的根路径下开始的
}
}
获取绝对路径的优点代码如下:
第一种:
package bj.powernode.javase.reflect;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class reflectTest05 {
public static void main(String[] args) throws IOException {
// 获取绝对路径
// 注意:必须src类的根目录开始
String path =Thread.currentThread().getContextClassLoader()
.getResource("Username.properties").getPath();
System.out.println(path); // /D:/IdeaProjects/javase/out/production/chapter9/Username.properties
// 以前读文件的老方法,需要写路径 这样写有可能我们换到其他系统种后文件夹就不正确了 文件名固定死了
// FileReader fileReader =new FileReader("chapter9\\src\\Username.properties");
// 我们可以通过拿到文件的绝对路径 然后进行读文件方法
FileReader fileReader =new FileReader(path); // 这样写 我们拿到哪个文件路径 就对哪个文件读取 不用担心在不同的系统了
// 创建map集合
Properties properties =new Properties(); // key和value都是String类型
// 把读到文件的内容加载到集合当中
properties.load(fileReader);
// 通过key获取value
String value =properties.getProperty("username");
System.out.println(value); // bj.powernode.javase.reflect.User
// 下面还可以进行反射机制操作 拿到User类
}
}
还有一种直接以流的形式返回:
package bj.powernode.javase.reflect;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class reflectTest05 {
public static void main(String[] args) throws IOException {
// 获取绝对路径
// 注意:必须src类的根目录开始
// 直接以流的形式返回
InputStream inputStream =Thread.currentThread().getContextClassLoader().getResourceAsStream("Username.properties");
// 创建map集合
Properties properties =new Properties(); // key和value都是String类型
// 把读到文件的内容加载到集合当中
properties.load(inputStream);
// 通过key获取value
String value =properties.getProperty("username");
System.out.println(value); // bj.powernode.javase.reflect.User
// 下面还可以进行反射机制操作 拿到User类
}
}