4

I am using eclipse to make a dynamic webpage. Its a simple program that relies on servlets to pass/retrieve data. One servlet of mine has to open a .txt file to read its content and send it to the client. However I get a FileNotFound Exception. I know its because I don't know how/where to place the txt file so that servlet can find that file at runtime. I am working on eclipse. Can you please provide some hints?

Thanks

bikashg
  • 721
  • 2
  • 13
  • 28

1 Answers1

6

Put it in the classpath (there where your Java code is) or add its path to the classpath.

InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("file.txt");

Or, put it in public webcontent (there where your JSP files also are).

InputStream input = getServletContext().getResourceAsStream("file.txt");

You should at least not use java.io.File with relative paths since that would be dependent on the current working directory which differs on the way how you start the application.

See also:

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • I understand you idea. Thanks for that. I have one more query. How about this : Lets say I have a servlet that calls upon another class(this one's not servlet, just a normal java class) to open a file, read it, send it to the servlet and the servlet will further send it to client. In that case, can I use the FileInputStream. Also, is this a good design practice? Please suggest. – bikashg Dec 11 '10 at 10:31
  • 1
    No, just put it in the classpath and load it from the classpath exactly as demonstrated in the 1st example in my answer. Then you're not dependent on environmental factors like where the webapp is installed and how the server is started and whether you've the servletcontext at your hands or not. The classpath works regardless of the environment and the kind/responsibility of the class. – BalusC Dec 11 '10 at 13:36
  • Thank you very much. Perfect solution. – bikashg Dec 12 '10 at 13:42
  • Hello @BalusC i got a simple question if i saved my file in "WEB-INF/Uploads/txt.txt" i can read it right ? thats what i know –  Feb 25 '14 at 09:27
  • 1
    @Amrola: yes, only not anymore after the redeploy of a WAR, assuming that it's really an uploaded file, for the very simple reason that this file is not contained in the original WAR. – BalusC Feb 25 '14 at 10:22
  • ah ok , thank you @BalusC –  Feb 25 '14 at 11:11
  • Just 2 comments: 1. If you put it under webcontent where your JSPs are, won't it be accessible directly from the client (undesirable)? 2. For maven projects, put the json file under src/main/resources and it will be available if you access it according to @BalusC first option. – ACV Apr 12 '16 at 09:57