java读取properties文件的方法

1.使用java.util.Properties类的load()方法java

示例:mysql

 //文件在项目下。不是在包下!!sql

 InputStream in = new BufferedInputStream(new FileInputStream("demo.properties")) ;  函数

Properties p = new Properties();学习

p.load(in) ;url

String className2 = p.getProperty("database.driver");spa

String url = p.getProperty("database.url");ssl

String user = p.getProperty("database.user");资源

String password = p.getProperty("database.pass");get


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 中


 不然就提示找不到文件(对于个人就是提示找不到)!!! 下面对这个文件我是放在src 下(就是在项目下/WEB-INF/classes)其实就是去找你的那个配置文件在哪里就好了。我很笨ing 的。因此一字一句的写,哪天健忘了,能够回来再看。


 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();

        鄙人菜鸟一个,但愿和你们一块儿学习,共同进步,若有不对的地方望你们纠正!

相关文章
相关标签/搜索