0

I am trying to connect to a database with phpMyadmin but I get an nullpointer in properties

Here is my code:

public Connection getConnection() throws SQLException {
        final String ip = prop.getProperty("database_ip");
        final String dir = prop.getProperty("database_dir");
        final String username = prop.getProperty("database_username");
        final String password = prop.getProperty("database_password");

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException("No suitable driver found");
        }
        return DriverManager.getConnection("jdbc:mysql://" + ip + "/" + dir, username, password);
    }

and here is where the nullpointer happens:

private Properties getPropertyFile(String path) {
        Properties prop = new Properties();
        try {
            prop.load(getClass().getClassLoader().getResourceAsStream(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return prop;
    }

and here is my map structure: enter image description here

shmosel
  • 49,289
  • 6
  • 73
  • 138
Nick Alexander
  • 361
  • 2
  • 5
  • 21
  • What line is the NullPointerException coming from? – Tyler Nov 08 '17 at 21:29
  • What `path` do you pass to `getPropertyFile`? Have you checked the resulting JAR file to ensure the resource is embedded in the JAR? (Not a experienced user with IntelliJ) is `resources` available to the classpath? Have you tried just `getClass().getResourceAsStream`? – MadProgrammer Nov 08 '17 at 21:31
  • see this answer for null returns from getResourceAsStream: https://stackoverflow.com/questions/16570523/getresourceasstream-returns-null – TheAtomicOption Nov 08 '17 at 21:35
  • on this line: prop.load(getClass().getClassLoader().getResourceAsStream(path)); – Nick Alexander Nov 08 '17 at 22:20
  • "dbconfig.properties" this path @MadProgrammer – Nick Alexander Nov 08 '17 at 22:21
  • @nick Maybe try `/dbconfig.properties` or `/resources/dbconfig.properties` – MadProgrammer Nov 08 '17 at 22:22
  • @MadProgrammer nope same error: java.lang.NullPointerException: null at java.util.Properties$LineReader.readLine(Properties.java:434) ~[na:1.8.0_74] at java.util.Properties.load0(Properties.java:353) ~[na:1.8.0_74] at java.util.Properties.load(Properties.java:341) ~[na:1.8.0_74] at dataaccess.init.Property.getPropertyFile(Property.java:22) ~[classes/:na] – Nick Alexander Nov 08 '17 at 22:25
  • Basically what it's trying to tell you is, the results of `getClass(). getResourceAsStream(...)` is `null`, you need to determine why. I'm not experienced with IntelliJ, so I can't suggest how you might check/fix this – MadProgrammer Nov 08 '17 at 22:30

0 Answers0