• 关于读取properties文件的方法


    第一种方法是使用InputStream字节流的方式,读取src下的properties文件,两种方式我都是以获取数据库的连接来举例子

    先贴出properties文件这是数据库的连接配置,这个文件在我项目工厂下的config包中路径为src/config/c3p0.properties

    jdbc_driver=com.mysql.jdbc.Driver
    jdbc_url=jdbc:mysql://localhost:3306/day101
    jdbc_password=123456
    jdbc_username=root
    
    private static String jdbcDriver = null;
    	private static String jdbcUrl = null;
    	private static String jdbcUsername = null;
    	private static String jdbcPassword = null;
    	static{
    		try {
    			Properties properties = new Properties();
    			//这里用了类加载器,加载类路径下的包为config下的c3p0.properties文件
    			InputStream inputStream = JdbcUtil.class.getClassLoader().getResourceAsStream("config/c3p0.properties");
    			//加载InputStream流
    			properties.load(inputStream);
    			//从properties文件中以key/value的方式读取配置数据
    			jdbcDriver = properties.getProperty("jdbc_driver");
    			jdbcUrl = properties.getProperty("jdbc_url");
    			jdbcUsername = properties.getProperty("jdbc_username");
    			jdbcPassword = properties.getProperty("jdbc_password");
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    	
    	public static Connection getConnection(){
    		try {
    			Class.forName(jdbcDriver);
    			return DriverManager.getConnection(jdbcUrl,jdbcUsername,jdbcPassword);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
    	public static void main(String[] args){
    		System.out.println(getConnection());
    	}
    

    第二种方式是用java.util提供的一个类ResourceBundle来读取properties文件的键值对,这种方式短小精悍

    properties文件跟上面的第一种方式一样

    我直接贴代码

    private static String jdbcDriver = null;
    	private static String jdbcUrl = null;
    	private static String jdbcUsername = null;
    	private static String jdbcPassword = null;
    	static{
    		ResourceBundle bundle = ResourceBundle.getBundle("config/c3p0");
    		jdbcDriver = bundle.getString("jdbc_driver");
    		jdbcUrl = bundle.getString("jdbc_url");
    		jdbcUsername = bundle.getString("jdbc_username");
    		jdbcPassword = bundle.getString("jdbc_password");
    	}
    	public static Connection getConnection(){
    		try {
    			Class.forName(jdbcDriver);
    			return DriverManager.getConnection(jdbcUrl,jdbcUsername,jdbcPassword);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
    	public static void main(String[] args){
    		System.out.println(getConnection());
    	}
    

      

  • 相关阅读:
    图片在网页中不能显示
    利用QQWry.dat显示客户IP所在地 [转贴]
    asp.net时间戳与系统时间互转 mssql
    酷友网 http://www.kuiu.cn/ 再次上线了!!!
    string.Format .net string 补空
    ASP.net中md5加密码的方法[转]
    C#中|(位或)和||(逻辑或)有什么区别?
    .net身份证号码验证
    实用jquery代码片段集合
    ERROR: “System.Web.Mvc.Controller.File(string, string, string)”是一个“方法”
  • 原文地址:https://www.cnblogs.com/tranquilityMan/p/11003293.html
Copyright © 2020-2023  润新知