java读取Properties配置文件

    技术2022-07-14  71

    一、使用Properties类

    Properties prop = new Properties(); //5种读取方式 prop.load(TestProperties.class.getClassLoader().getResourceAsStream("application.properties"));//1、从当前类加载器的getResourceAsStream方法读取 prop.load(new FileInputStream(new File("C://application.properties")));//2、从文件读取 prop.load(ClassLoader.getSystemResourceAsStream("C://application.properties"));//3、通过classloader读取 prop.load(context.getResourceAsStream("C://application.properties"));//4、通过context来读取 prop.load(new URL("url").openStream());//5、通过url来读取 String key = prop.getProperty("username");

    二、使用ResourceBundle类(推荐)

    ResourceBundle res = ResourceBundle.getBundle("application");//读取配置文件内容 if(res.containsKey("username")){//判断属性是否存在,直接读取不存在的属性会抛异常 String value=new String(res.getString("username").getBytes("ISO-8859-1"), "UTF-8");//解决乱码问题 }

     

     
    Processed: 0.009, SQL: 9