java读取.properties配置文件

1、使用java.util中Properties类和类加载器

private static Properties props = new Properties();

static{

  try{

      InputStream in =  Ca.Class.getClassLoader.getResourceAsStream("bean.properties");

      props.load(in);

}catch(Exception e){

throw new ExceptionInInitializerError(e);

}

}

后面用的时候就是比如:

String  name = props.get("name");


2、使用java.util中Properties类和FileInputStream  


private static Properties props = new Properties();

static{

  try{

      InputStream in = new  FileInputStream("src/bean.properties");

      props.load(in);

}catch(Exception e){

throw new ExceptionInInitializerError(e);

}

}

后面用的时候就是比如:

String  name = props.get("name");

注:此种方法一般不要用,因为如果部署到服务器上,会找不到配置文件的路径。

3、使用ResourceBundle

private  static ResourceBundle bundle = ResourceBundle.getBundle("bean");

后面用的时候就是比如:

String  name = bundle.getString("name");

注:此种方法有如下特点

1、它只能用于读取properties文件,别的文件读不了

2、只能用于读取,不能用于写入

3、只能读取类路径下的文件,别的路径下读不了

4、方法参数的写法是按照包名.类名的方式写的,所以请不要写扩展名。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容