简体   繁体   中英

Run an application that reads and writes external text files in java servlet

I am new to java servlet. I am writing an application that reads and writes text files. However, I am running this application on a java servlet using JSP. When I ran the servlet in eclipse, it keeps reporting file not found error. I really don't know how to correct the file path so that servlet won't complain about it.

Basically, the application and servlet code are in the same src folder, but different packages. Could you please tell me where I should place these text files and how I should read and write them? Thank you very much.

Some Info

  • Files that are in a web applications context root are browsable by clients. I suspect this is not a desired feature.
  • Files that are under the WEB-INF folder in your web application are accessable to the web application, but are not browsable by clients.

Suggested Solution 1

  • Plan to put the files in a folder under the WEB-INF folder; perhaps named "Files" ( ie "WEB-INF/Files").
  • Use ServletContext.getRealPath() to get the real file path.
  • Read and write the files using java IO (BufferedReader, Scanner, something else - you choose).

Sugested Solution 2

Based on comments below. The servlet will be part of a web application that is installed into a servlet container (maybe Tomcat) on a known host. Create a directory on the host. Add this directory to the servlet as a parameter (maybe servlet config, maybe a properties file, maybe a hard coded string, or any other solution). Once this is done, the servlet will know where to read and write the files. At that point, any application can read and write to the files in question.

No need to use getRealPath() with this solution, the real path is a parameter to the servlet.

Suggested Reading List

For an introduction (possibly dated, but still good), read the "Intermediate Servlets & JSP" and "Advanced Servlets & JSP" tutorials on the Core Servlets website.

Another introduction source is the Java EE 5 Tutorial . The entire tutorial is good, but focus on Part II, chapters 3 and 4 for servlet information. I prefer this tutorial to the Java EE 6 Tutorial , but that may just be personal preference.

The default directory is the directory of your project. Put your files in the project directory, for me it is "C:\\Documents and Settings\\myusername\\workspace\\projectname".

You can place the file everywhere you want but i sugget to you to put it under WEB-INF so it can't be accessed directly.

You can access it using:

getServletContext().getRealPath("/WEB-INF/filename");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM