2.可以通过当前线程 Thread.currentThread().getContextClassLoader().getResource获取
public class TestDemo {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties pro=new Properties();
TestDemo test=new TestDemo();
pro.setProperty("url", "localhost:8080");
pro.setProperty("username", "root");
pro.setProperty("password", "123");
String filepath="G:/util/";
//pro.store(new FileOutputStream(new File("db.properties")), "资 源配置");
File file =new File(filepath);
if(!file.exists()){
file.mkdir();
}
File realpath=new File(file,"db.properties");
if(!realpath.exists()){
realpath.createNewFile();
}
//写入properties文件
pro.store(new FileOutputStream(realpath), "properties配置");
File xmlpath=new File(file,"db.xml");
if(!xmlpath.exists()){
xmlpath.createNewFile();
}
//写入xml文件中
pro.storeToXML(new FileOutputStream(xmlpath), "xml配置");
//加载配置文件
Properties pro1=new Properties();
// pro1.load(TestDemo.class.getClassLoader().getResourceAsStream("test/db.properties"));
//获取文件的相对路径
//1.可以通过 类名。class.getResource方法获取或者getSystemResource
//2.可以通过当前线程 Thread.currentThread().getContextClassLoader()。getResource获取
pro1.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("test/db.properties"));
System.out.println(TestDemo.class.getResource("/test/db.properties"));
System.out.println(Thread.currentThread().getContextClassLoader().getResource("test/db.properties"));
//System.out.println(Thread.currentThread().getContextClassLoader().getSystemResource("test/db.properties"));
System.out.println(test.getClass().getClassLoader().getResourceAsStream("test/db.properties"));
System.out.println(TestDemo.class.getResource("/"));//斜杠代表从根路径 开始
System.out.println(TestDemo.class.getResource(""));//空格代表当前类的相对路径开始
System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));//空格代表从根路径开始
String str= pro1.getProperty("password", "没找到");
System.out.println(str);
}
}