读写属性文件

把有关数据库配置的信息写在文件中,并且保存在项目内,在程序中读取文件中的信息,从而进行数据库连接. 在Java中提供了Properties类,来读取 .properties(属性)文件. 在项目默认路径(src)下创建文件.名称为 db.properties(名称可自定义,扩展名必需为properties),编辑文件内容所下所示:
driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
url=jdbc:microsoft:sqlserver://localhost:1433;databaseName=books
user=sa
password=1200

在程序调用Properties类的load()方法时,系统把db.properties文件的内容加载到内存中.因为Properties类继承了Hashtable,Properties类把"="之前的内容,如driver,url等,等添加到Hashtable对象的Key值,并同时添加key值对应的value,也就是"="右侧的值.所以在编写.properties文件时一定要使用"="号把名称与值分隔开呐..呵呵...
(注:通过.properties文件形式只能保存String类型信息)

=====================================================
package haha;
import java.util.Properties;
import java.io.IOException;
import java.io.InputStream;
public class Env extends Properties {
private static Env instance;
public static Env getInstance() {
  // 以单例模式创建,获得对象实例
  if (instance != null) {
   return instance;
  } else {
   makeInstance();
   return instance;
  }
}
// 同步方法。保证在同一时间,只能被一个人调用呐。呵呵。。
private static synchronized void makeInstance() {
  if (instance == null) {
   instance = new Env();
  }
}
private Env() {
  InputStream is=getClass().getResourceAsStream("/db.properties");
  try {
   load(is);
  } catch (IOException e) {
   e.printStackTrace();
   System.out.println("错误:没有读取属性文件,请确认db.properties文件是否存在!!!");
  }
}
}

==============================================================
package haha;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManager {
public static synchronized Connection getConnection() {
  //读取配置信息
  String driverClassName=Env.getInstance().getProperty("driver");
  String url=Env.getInstance().getProperty("url");
  String password=Env.getInstance().getProperty("password");
  String user=Env.getInstance().getProperty("user");
  Connection connection=null;
  try {
   Class.forName(driverClassName);
   connection=DriverManager.getConnection(url,user,password);
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  return connection;
}
...............// 关闭连接方法
}
原文地址:https://www.cnblogs.com/soundcode/p/1911905.html