db.properties这个文件我想放在src目录下,现在一运行这个Test类在p.load(is);这句就报异常了;
db.properties
[code="java"]
DRIVER=com.microsoft.sqlserver.jdbc.SQLServerDriver
username=sa
password=sasa
url=jdbc:sqlserver://localhost:1433;DatabaseName\=Wss[/code]
[code="java"]
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class Test {
private static Connection conn = null;
String sDbDriver = null;
String sConnection = null;
String sUser = null;
String sPassword = null;
public void CreateConn(){
try{
InputStream is = getClass().getResourceAsStream("/db.properties");
Properties p = new Properties();
p.load(is);
sDbDriver = p.getProperty("DBDriver",sDbDriver);
System.out.println(sDbDriver);
sConnection = p.getProperty("Connection", sConnection);
sUser = p.getProperty("username",sUser);
sPassword = p.getProperty("password",sPassword);
Properties pr = new Properties();
pr.put("user", sUser);
pr.put("password", sPassword);
pr.put("characterEncoding", "GB2312");
pr.put("userUnicode", "TRUE");
Class.forName(sDbDriver).newInstance();
conn = DriverManager.getConnection(sConnection,pr);
System.out.println("数据库连接成功!");
}catch(Exception ex){
System.out.println("conn bad!");
ex.printStackTrace();
}
}
public static void main(String[] args){
Test dbc = new Test();
try{
dbc.CreateConn();
}catch(Exception e){
e.printStackTrace();
}
}
}
[/code]
报错信息
[code="java"]
conn bad!
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
at com.db.Test.CreateConn(Test.java:19)
at com.db.Test.main(Test.java:44)
[/code]