Reputation: 1056
I am using config.properties file in order to set port. After running I am facing an error:
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException at
java.util.Properties$LineReader.readLine(Properties.java:434) at
java.util.Properties.load0(Properties.java:353) at
java.util.Properties.load(Properties.java:341) at
HttpServer.setPort(HttpServer.java:83) at
HttpServer.(HttpServer.java:26)
The main class:
public class HttpServer {
static final boolean SSL = System.getProperty("ssl") != null;
static final int PORT = Integer.parseInt(System.getProperty("port", SSL ? "8443" : setPort()));
public static void main(String[] args) {
HttpServer httpServer = new HttpServer();
httpServer.start();
}
public void start(){}
public static String setPort() {
String port = "";
Properties properties = new Properties();
try {
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("src/main/config.properties"));
port = properties.getProperty("server.port");
} catch (IOException e) {
e.printStackTrace();
}
return port;
}
}
I am not able to understand what is the error...
Upvotes: 3
Views: 35553
Reputation: 9415
It looks like your code is in a maven project. As such,
src/main/resources/config.properties
getResourceAsStream("/config.properties")
When doing a maven build, maven will package your jar and make the resources part of the classpath. Anything in resources/
will be part of the classpath root, since I start it with a slash when I use the getResourceAsStream
.
You could also have simply called:
HttpServer.class.getResourceAsStream("/config.properties")
instead.
Note that you open a InputStream, and pass it to Properties.load()
. This will leave the stream open. Better to do something like:
try (InputStream is = HttpServer.class.getResourceAsStream("/config.properties") ) {
properties.load(is);
}
The Try-With-Resources will take care of closing the input stream no matter what ( even in case of an error/exception).
Many do not do that, and even I leave it open for short running programs ... But yours suggests it is a HTTP Server ... so better to be more sensitive about these mattes ... connection leaks, file handle leaks, memory leaks, etc. Eventually it might get garbage collected, but better not to depend on it.
Upvotes: 4