我需要在Java中使用.properties
文件来存储数据库信息。
这是我的数据库连接器类。它给出了 NullPointerException
。我的代码有什么问题?
请注意,我还没有分配那些属性文件值。数据库连接值仍然是硬编码的。
import java.io.IOException;
import java.io.InputStream;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public final class Database {
public Connection connection;
private Statement statement;
private Properties property;
public static Database database;
private Database() {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "edus";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
try {
InputStream is = Database.class.getClassLoader().getResourceAsStream(
"config.properties");
property.load(is);
System.out.println(property.getProperty("db_user"));
System.out.println(property.getProperty("db_password"));
System.out.println(property.getProperty("db_name"));
Class.forName(driver).newInstance();
this.connection = (Connection) DriverManager.getConnection(url + dbName,
userName, password);
}catch (IOException ex) {
Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException e) {
System.out.println("JDBC driver is missing");
} catch (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
public static synchronized Database getDatabaseConnection() {
if (database == null) {
database = new Database();
}
return database;
}
}
最佳答案
config.properties 不在类路径下。它应该在类文件夹下。
你也可以试试
Database.class.getClassLoader().getResourceAsStream(
"com/lk/apiit/eduservice/config.properties");
正如 Roman C 指出的,您还需要先初始化 Properties 对象
Properties property = new Properties();
关于java - 如何使用 Java 属性文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20314938/