Read a resource file inside JSF application

后端 未结 1 819
囚心锁ツ
囚心锁ツ 2020-12-16 07:52

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

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

However, the system do

相关标签:
1条回答
  • 2020-12-16 08:29

    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:

    • getResourceAsStream() vs FileInputStream
    • Accessing properties file in a JSF application programmatically
    • Where to place and how to read configuration resource files in servlet based application?
    • What does servletcontext.getRealPath("/") mean and when should I use it
    0 讨论(0)
提交回复
热议问题