Search code examples
javamanaged-bean

How to specify file path in Java Bean in a web application?


I want to read models.txt in WebContent/resources/db/ from IndexBean.java in src/DataTable/. How shall I set the filePath in

sc = new Scanner(new File(filePath));

I know I can achieve this by absolute path, but want to know how to do it in relative path.

capture

And another interesting thing is: In IndexBean.java which is a Java Bean, if I run the following code, I will get the path of eclipse.exe. While if I run the same code in testFileRead.java in the same package which is not a Java Bean, I will get the path of the workspace of the application. Could someone explain this? Thanks!

File dir1 = new File("..");
try {
    System.out.println("Current dir : " + dir1.getCanonicalPath());
} catch (IOException e1) {
    e1.printStackTrace();
}

Solution

  • First of all, these kind of internal files should reside in an inaccessible spot, in WebContent/WEB-INF.

    You could get a file system File:

    File file = request.getServletContext().getRealPath("/resources/db/models.txt");
    

    If you store the file as real resource (in the class path), you can use:

    InputStream in = getClass().getResourceAsStream("/db/models.txt");
    

    Please specify the character encoding:

    sc = new Scanner(new File(filePath), "UTF-8");
    

    So the same encoding is used whether developing under Windows or deploying on a Linux server. Because the default encoding is platform dependent.


    ServletContext servletContext = (ServletContext)
        FacesContext.getCurrentInstance().getExternalContext().getContext();