How to read a configuration file in Java

devsda picture devsda · Apr 29, 2013 · Viewed 146.7k times · Source

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 ?

Answer

Fakhredin Gholamizadeh picture Fakhredin Gholamizadeh · Aug 25, 2018

app.config

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

Source code:

Properties prop = new Properties();
String fileName = "app.config";
InputStream is = null;
try {
    is = new FileInputStream(fileName);
} catch (FileNotFoundException ex) {
    ...
}
try {
    prop.load(is);
} catch (IOException ex) {
    ...
}
System.out.println(prop.getProperty("app.name"));
System.out.println(prop.getProperty("app.version"));

Output:

Properties Sample Code
1.09