3

I need to grab a resource file inside my JSF application.

InputStream input = new FileInputStream("filename.xml");

However, the system does not find filename.xml file, which is in the same folder as the sample.xhtml web page. How do I get an InputStream of it?

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
ollo
  • 99
  • 2
  • 9

1 Answers1

11

The FileInputStream works directly on the local disk file system. It knows nothing about the context the application is running on. It absolutely doesn't know anything about WAR file structures, classpath resources and web resources.

Any relative path (i.e. any path not starting with a drive letter or a slash) which you pass to FileInputStream is interpreted relative to the current working directory, which is the folder which is opened at exactly the moment the Java Virtual Machine is started by java.exe command. You can figure the exact path as follows:

System.out.println(new File(".").getAbsolutePath());

Chances are very big that this is not the location you expected to be. Otherwise you wouldn't have asked this question in first place. Usually it refers the IDE's workspace folder, or the server's binary folder, or the currently opened folder in command prompt, depending on the way how you started the server.

If the file is placed in the classpath as a classpath resource, i.e. you placed it in "Java Sources" in a com.example package, then you should be obtaining an InputStream of it as follows:

InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/example/filename.xml");
// ...

Or, if it is guaranteed to be visible to the same classloader as the current class, and you're not in static context, then you could also do so (yes, with a leading slash as opposed to the context class loader!):

InputStream input = getClass().getResourceAsStream("/com/example/filename.xml");
// ...

Or, if it is in the same package as the current class:

InputStream input = getClass().getResourceAsStream("filename.xml");
// ...

Or, if the file is placed in the webcontent as a web resource, i.e. you placed it in "Web Content" in the same folder as where you can also find /WEB-INF, /META-INF and so on, then you should be obtaining an InputStream of it as follows:

InputStream input = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/filename.xml");
// ...

See also:

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452