1. 程式人生 > >java中讀取資原始檔的方法

java中讀取資原始檔的方法

1.使用java.util.Properties類的load()方法 示例: //檔案在專案下。不是在包下!! InputStream in = new BufferedInputStream(new FileInputStream("demo.properties")) ; Properties p = new Properties(); p.load(in) ; String className2 = p.getProperty("database.driver"); String url = p.getProperty("database.url"); String user = p.getProperty("database.user"); String password = p.getProperty("database.pass"); 2. 使用java.util.Resourcebundle類的getbundle()方法 //前面沒有“/”代表當前類的目錄 示例: //檔案和類在同一個包下,注意它的檔名和字尾!!是調換的, ResourceBundle resource = ResourceBundle.getBundle("properties.jdbc"); String className = resource.getString("database.driver"); String url = resource.getString("database.url"); String user = resource.getString("database.user"); String password = resource.getString("database.pass"); 3.使用java.util.PropertyResourceBundle類的建構函式 示例: // 檔案在專案下 或者 src/demo.properties // 在 src/demo.properties 寫成 new FileInputStream("src/demo.properties") InputStream in = new BufferedInputStream(new FileInputStream("demo.properties")); ResourceBundle rb = new PropertyResourceBundle(in) ; String className4 = rb.getString("database.url"); 4.使用class變數的getresourceasstream()方法 示例: InputStream in =Properties.class.getResourceAsStream("/properties/jdbc.properties"); // 包點類名下的。 // 如果找不到帶有該名稱的資源,則返回 null Properties p = new Properties(); p.load(in); System.out.println(p.getProperty("database.url")); 5.使用class.getclassloader()所得到的java.lang.classloader的getresourceasstream()方法 // properties 檔案 要放在src下面,否則找不到啊 示例: InputStream in = 類名.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties p = new Properties() ; p.load(in); System.out.println(p.getProperty("database.pass")); 6.使用java.lang.classloader類的getsystemresourceasstream()靜態方法 示例: // 同包名下 InputStream in = ClassLoader.getSystemResourceAsStream("properties/jdbc.properties"); Properties p = new Properties() ; p.load(in) ; System.out.println(p.getProperty("database.user")); 總結:如果是 在WEB上讀取properties檔案,寫成下面這種。上面寫的那些只在 JavaSE 中 String path = Thread.currentThread().getContextClassLoader().getResource("").getPath(); System.out.println(path); InputStream in = new FileInputStream(new File(path+File.separator+"mysql.properties")); Properties prop = new Properties();