Reputation: 101
I'm trying to write a simple code to communicate with the database. But it gives an error. The application.properties file contains a link to the localhost, username and password. In three lines. image exception text
Main.java
public static void main(String[] args) throws SQLException {
Class<Driver> driverClass = Driver.class;
try (var connection = ConnectionManager.open()) {
System.out.println(connection.getTransactionIsolation());
}
}
}
ConnectionManager.java
public final class ConnectionManager {
private static final String PASSWORD_KEY = "db.password";
private static final String USERNAME_KEY = "db.username";
private static final String URL_KEY = "db.url";
static {
loadDriver();
}
private ConnectionManager() {
}
public static Connection open() {
try {
return DriverManager.getConnection(
PropertiesUtil.get(URL_KEY),
PropertiesUtil.get(USERNAME_KEY),
PropertiesUtil.get(PASSWORD_KEY)
);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
private static void loadDriver() {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
PropertiesUtil.java
public final class PropertiesUtil {
private static final Properties PROPERTIES = new Properties();
static {
loadProperties();
}
private PropertiesUtil() {
}
public static String get(String key) {
return PROPERTIES.getProperty(key);
}
private static void loadProperties() {
try (var inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream("application.properties")) {
PROPERTIES.load(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Upvotes: 0
Views: 92
Reputation: 101
The problem was solved by moving the application.properties file to the root directory in src. In idea, you can mark the file as "resources root" and the file seems to be in the root directory. I didn't find this in vs code.
Upvotes: 1
Reputation: 102902
Learn how to understand errors. The error is clearly saying that inputStream
in the line PROPERTIES.load(inputStream)
is null
. This is because:
PropertiesUtil.class.getClassLoader().getResourceAsStream("application.properties")
is trying to load a resource that does not exist. I think you're misunderstanding / mis-using gRAS here:
PropertiesUtil.class.getResourceAsStream("/application.properties")
There is no non-hacky/easy way to find 'the location where my jar resides', so you may not want to do that. One easy solution is to load from the user's home dir:
try (var in = Files.newInputStream(Paths.get(System.getProperty("user.home"), "application.properties"))) {
PROPERTIES.load(in);
}
Upvotes: 0