1

My project directory looked like this

enter image description here

I am getting the following error

Exception in thread "main" java.io.FileNotFoundException: /resources/config.properties (No such file or directory) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.(FileInputStream.java:138) at java.io.FileInputStream.(FileInputStream.java:93) at quartztest.QuartzTest.main(QuartzTest.java:36) /home/seng/.cache/netbeans/8.1/executor-snippets/run.xml:53: Java returned: 1 BUILD FAILED (total time: 0 seconds)

My code as below

Properties prop = new Properties();
InputStream input = null;

input = new FileInputStream("/resources/config.properties");
prop.load(input);
Chris
  • 7,675
  • 8
  • 51
  • 101
Cyndi
  • 59
  • 1
  • 9

4 Answers4

2

First of all, starting with a "/" means that your search starts from root, not from a subdirectory.

Next to that the resource folder is probably in you project folder so you have to use the getClass().getClassloader()... to read a file. And you then can only use the file name (if it is unique), otherwise you have to provide the path to make it unique.

If you use the FileInputStream you have to provide the whole path to the file.

Hans Schreuder
  • 745
  • 5
  • 10
1

As the resources folder is a source folder, you can get an InputStream with:

input = QuartzTest.class.getResourceAsStream("/resources/config.properties");
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
1

I see two options here:

  1. input = new FileInputStream("src/main/resources/config.properties");
  2. ClassLoader classloader = Thread.currentThread().getContextClassLoader(); InputStream is = classloader.getResourceAsStream("config.properties"); The second one is preferred because you need to specify relative path according to resource folder

If you don't use this from static context, you can simplify retrieving classloader to

ClassLoader classLoader = getClass().getClassLoader();
Maksym Rudenko
  • 706
  • 5
  • 16
0

Try using this to load:

//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("config.properties").getFile());
GuyKhmel
  • 505
  • 5
  • 15