private static Properties pp=null;//读配置文件
private static FileInputStream fis=null;
static{//只需要加载一次,所以放在静态代码块里
try {
//从dbinfo.properties中读取配置信息
String path = Thread.currentThread().getContextClassLoader().getResource("dbinfo.properties").getPath();
fis = new FileInputStream(path);
pp=new Properties();
pp.load(fis);
url=pp.getProperty("url");
username=pp.getProperty("username");
driver=pp.getProperty("driver");
password=pp.getProperty("password");
Class.forName(driver);
读取propertites配置文件,出现“系统找不到指定的文件”
通过上面的语句进行正确加载,同时dbinfo.properties文件要放在src目录下
这涉及到一个Tomcat主目录的问题,Tomcat的主目录默认是在bin目录下,如果使用
fis=new FileInputStream("dbinfo.properties");
pp.load(fis)
来加载文件,则需要把这个properties文件放在bin目录下才可以
当我们使用java web的时候,读取文件需要使用类加载器,因为类加载器的去读取资源的时候默认路径是src
private static Properties pp=null;//读配置文件
private static FileInputStream fis=null;
private static InputStream in=null;
static{//只需要加载一次,所以放在静态代码块中
try {
//从dbinfo.properties中读取配置信息
//String path = Thread.currentThread().getContextClassLoader().getResource("dbinfo.properties").getPath();
//fis = new FileInputStream(path);
//当我们使用java web的时候,读取文件需要使用类加载器
in=SqlHelper.class.getClassLoader().getResourceAsStream("dbinfo.properties");
pp=new Properties();
pp.load(in);
url=pp.getProperty("url");
username=pp.getProperty("username");
driver=pp.getProperty("driver");
password=pp.getProperty("password");
Class.forName(driver);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
//fis.close();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
in=null;
}