Issues with loading properties files using FileInputStream

Image

App.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.my;
 
import java.io.FileInputStream;
import java.util.Properties;
 
public class App
{
	public static void main( String[] args )
	{
		String var = null;
		Properties properties = new Properties();
		try {
			properties.load(new FileInputStream("test.properties"));
			var = (String) properties.get("my.prop");
			System.out.println(var);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

In the above figure folder structure if we run App.java from C:/TestingAppsresourcetest i.e. the same directory which has test.properties using the following command, it will work ok.

C:/TestingAppsresourcetest>java -cp “.;target/classes” com.my.App
hello

However, if we ran App.java from a different directory it would throw an error.

C:/TestingAppsresourcetesttargetclasses>java com.my.App
java.io.FileNotFoundException: test.properties (The system cannot find the file
specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at com.my.App.main(App.java:19)

So if you use FileInputStream to load properties. Use relative paths to properties files and end up changing the running directory (like we did), then you will face issues.