0

We are trying to read a property file in a servlet using fileInputStream.

However we are constanlty getting a file not found exception.

This is the piece of code we are using

Properties properties = new Properties();
          File propertyFile = new File("config" + File.separatorChar + "abc.properties");
          try {
          FileInputStream propertyFileStream = new FileInputStream(propertyFile);
                properties.load(propertyFileStream);
                propertyFileStream.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

While using getResourceAsStream it is working fine.

However we need to understand why FileInputStream is not working.

We have placed the config\abc.properties file in the webInf. We have also tried placing it in the src folder(java classpath), the webContent folder, the WebInf\Classes folder but no success.

sidgate
  • 14,650
  • 11
  • 68
  • 119
user123
  • 111
  • 1
  • 6

3 Answers3

0

Resources are not files. They don't live in the file system and they cannot be accessed via File or FileInputStream.

You should be using Class.getResource().

user207421
  • 305,947
  • 44
  • 307
  • 483
0

Try by using

  ResourceBundle resource = ResourceBundle.getBundle("test");
  String VALUE1=resource.getString("KEY1");
  String VALUE2=resource.getString("KEY2");
KhAn SaAb
  • 5,248
  • 5
  • 31
  • 52
  • ok. but why doesnt FileInputStream works....as in why this works for standalone but not in case of web ? – user123 May 13 '16 at 10:10
0

You should use this code to get resources on web application, because the path must be taken from ServletContext, I think that's what you're looking for, if you are inside Servlet:

InputStream is = getContext().getResourceAsStream("/WEB-INF/yourFolder/abc.properties");

to get the full path for your interest:

String fullPath = getContext().getRealPath("/WEB-INF/yourFolder/abc.properties");
M. Mariscal
  • 1,226
  • 3
  • 17
  • 46