0

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();
}
1
  • 1
    This question is not related with Eclipse nor JSF nor JavaBeans. Again, if you're working with Managed Beans, call them like that, not as java beans. Commented Jun 6, 2013 at 14:58

2 Answers 2

3

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();
Sign up to request clarification or add additional context in comments.

4 Comments

So I should move the resources folder under WEB-INF? Why?... Thanks!
I guess I should declare request as HttpServletRequest and it should be String filePath(instead of File file) = request.getServletContext().getRealPath("/resources/db/models.txt");?
Right. ServletRequest may be cast to HttpServletRequest.
Added how to retrieve the ServletContext from JSF.
0

I think @Joop Eggen has proposed the best solution for you. However, sometimes you can set a environment variable to your file path and you can change it as you push your code through different environment.

 String dir = System.getProperty("user.dir");

1 Comment

Especially sensible for dynamic data, files you write to. Then you can deploy a .war without the file. Or massive file uploads.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.