How to read a configuration file in Java

JavaConfiguration Files

Java Problem Overview


I am doing a project to build thread pooled web server, in which I have to set

  • the port number on which server listens.
  • How many threads are there in thread pool
  • Absolute Path of the root directory, and so many points.

One way is to hard code all these variables in the code, that I did. But professionally it is not good.

Now, I want to make one configuration file, in which I put all these data, and at the run time my code fetches these.

How can I make configuration file for the above task ?

Java Solutions


Solution 1 - Java

app.config

app.name=Properties Sample Code
app.version=1.09  

Source code:

Properties prop = new Properties();
String fileName = "app.config";
try (FileInputStream fis = new FileInputStream(fileName)) {
    prop.load(fis);
} catch (FileNotFoundException ex) {
    ... // FileNotFoundException catch is optional and can be collapsed
} catch (IOException ex) {
    ...
}
System.out.println(prop.getProperty("app.name"));
System.out.println(prop.getProperty("app.version"));

Output:

Properties Sample Code
1.09  

Solution 2 - Java

It depends.

Start with Basic I/O, take a look at Properties, take a look at Preferences API and maybe even Java API for XML Processing and Java Architecture for XML Binding

And if none of those meet your particular needs, you could even look at using some kind of Database

Solution 3 - Java

Create a configuration file and put your entries there.

SERVER_PORT=10000     
THREAD_POOL_COUNT=3     
ROOT_DIR=/home/   

You can load this file using Properties.load(fileName) and retrieved values you get(key);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondevsdaView Question on Stackoverflow
Solution 1 - JavaFakhredin GholamizadehView Answer on Stackoverflow
Solution 2 - JavaMadProgrammerView Answer on Stackoverflow
Solution 3 - JavaprasanthView Answer on Stackoverflow