1.可以通過 類名.class.getResource方法獲取或者getSystemResource
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);
} }