I am no newcomer to Java. One thing that confounds me is why it is so messy to load values from .properties files.
I have an application where, if the .properties file is found, then the value if found, should be used. And in any other circumstance, to use the default. (In the correct deployment, the server is run with sufficient permissions to engage with the socket listener 443, whereas in the development environment or any other environment where a person goes to the trouble to insert the .properties file, another port will be used).
The location of the file is com/foo/bar/webserver.properties
in the in the same directory as the class file com/foo/bar/WebServer.class
.
The content of webserver.properties
is simply:
listen=4444
Since this such a terribly simple function I would like to know if the community of reviewers sees a more elegant/succinct/secure/complete/correct way to load the value. I feel like I must be overlooking something basic for what feels like, to me, should be a one-liner more like the imaginary API:
// set int value for key "listen", or else default value 443
int port = Properties.loadProperties( "webserver.properties" ).getInt( "listen", 443 );
And here is my real code for review:
int port;
try ( InputStream webserverProperties = WebServer.class.getResourceAsStream( "webserver.properties" ) ) {
if ( webserverProperties == null ) {
port = 443;
} else {
Properties p = new Properties();
p.load( webserverProperties );
String listen = p.getProperty( "listen", "443" );
port = Integer.parseInt( listen );
}
}
catch ( NumberFormatException e ) { port = 443; }
finally {}
Properties
class is old, and it shows. It's also designed specifically to work only withString
values. It sounds like it's not a great choice for the problem you've got. You might want to consider using a different abstraction or writing your own. It shouldn't be that hard to compose aProperties
instance into the fluent API you're describing as your ideal. \$\endgroup\$