public class DBBase { private static Properties config=new Properties(); static{ InputStream in = DBBase.class.getResourceAsStream("/dbconfig.properties"); if(in==null){ throw new RuntimeException("the file is not found!"); } try { config.load(in); in.close(); } catch (IOException e) { //e.printStackTrace(); throw new RuntimeException("load fail "+e.getMessage()); } } public Connection conn=null; private String driver=config.getProperty("driver"); private String url=config.getProperty("url"); private String user=config.getProperty("username"); private String pass=config.getProperty("password"); public DBBase(){ try { Class.forName(driver); conn=DriverManager.getConnection(url,user,pass); } catch (ClassNotFoundException e) { System.out.println("找不到驱动"); e.printStackTrace(); } catch (SQLException e) { System.out.println("链接失败"); e.printStackTrace(); } } } 这里需要注意的是资源文件应该和类在同一目录下,如果资源文件在工程的根目录下,则Class.getResourceAsStream("/dbconfig"); 这里路径参数前面需要加“/”。 dbconfig.properties driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/*** username=*** password=***