在Java程序中,一般情況下使用絕對路徑還是相對路徑都不太合適,因為Java程序的jar包所放的位置不確定,執行java程序時當前的路徑也不確定,所以不合適。一般在Java程序中我們會把資源放到classpath中,然后使用classpath路徑查找資源。
1.獲取classpath中的資源(InputStream)
public class Demo1 { static Properties properties; static{ properties = new Properties(); try { Class clazz = Demo1.class; // 開頭的'/'表示classpath的根目錄,這個是表示從classpath的根目錄中開始查找資源,如果開頭沒有'/',表示從當前這個class所在的包中開始查找 InputStream inputestream = clazz.getResourceAsStream("/db.properties"); properties.load( inputestream); } catch (IOException e) { } } @Test public void DBUtil(){ System.out.println("username:"+properties.getProperty("username")+ " password:"+properties.getProperty("password")); } }
2.Properties配置文件
加載配置文件
public class DBUtil { static Properties properties = new Properties(); static{ try { Class clazz = DBUtil.class; InputStreamReader fileReader = new InputStreamReader(clazz.getResourceAsStream("/db.properties")); properties.load(fileReader); } catch (IOException e) { e.printStackTrace(); } } public static String getUserName(){ String userName =properties.getProperty("userName"); return userName; } public static String getPassword(){ return properties.getProperty("password"); } public static void main(String[] args) { System.out.println("用戶名:"+ getUserName()); System.out.println("密碼: "+ getPassword()); } }
寫配置文件
public static void testStoreProperties() throws Exception { // 准備配置信息 Properties properties = new Properties(); properties.setProperty("name", "李四"); properties.setProperty("age", "20"); // 准備 OutputStream out = new FileOutputStream("d:/my.properties"); String comments = "這是我的配置文件"; // 寫出去 properties.store(out, comments); out.close(); }