获取路径的方式
- 路径的选择是必要的,同时我们也需要保证路径的可移植性,所以我们应该使用一种通用的路径方式来完成需求
- 使用通用方式的前提:文件必须在类路径下,类路径即src(src是类的根路径)
方式一
- 语法格式:
String path = Thread.currentThread().getContextClassLoader().getResource("以src为根的路径名").getPath();
Thread.currentThread() :当前线程对象
getContextClassLoader() :获取到当前线程的类加载器对象(线程对象的方法)
getResource() :获取资源,当前线程的类加载器默认从类的根路径下加载资源(类加载器对象的方法)
getPath():获取路径(文件类File的方法)
import java.io.FileReader;
import java.util.Properties;
public class Test {
public static void main(String[] args) throws Exception {
String path = Thread.currentThread().getContextClassLoader().getResource("test.properties").getPath();
FileReader reader = new FileReader(path);
Properties pro = new Properties();
pro.load(reader);
reader.close();
String name = pro.getProperty("name");
System.out.println(name);
}
}
方式二
- 以流的方式返回
- 语法格式:
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("");
Reader reader = Thread.currentThread().getContextClassLoader().getResourceAsReader("");
import java.io.InputStream;
import java.util.Properties;
public class Test {
public static void main(String[] args) throws Exception {
InputStream reader = Thread.currentThread().getContextClassLoader().getResourceAsStream("test.properties");
Properties pro = new Properties();
pro.load(reader);
reader.close();
String name = pro.getProperty("name");
System.out.println(name);
}
}
方式三
- java.util 包下提供了一个资源绑定器ResourceBundle,便于获取属性配置文件中的内容
- 资源绑定器只能绑定xxx.properties文件,并且这个文件必须在类路径下,文件扩展名也必须是 .properties,代码中写路径的时候,路径后面的扩展名不写
public class Test {
public static void main(String[] args) throws Exception {
ResourceBundle bundle = ResourceBundle.getBundle("com/lzj/reflect/bean/db");
String name = bundle.getString("name");
System.out.println(name);
}
}