简体   繁体   中英

Reading external file from a servlet

whenever I am reading or writing a file in a servlet using new File() without using absolute path, the path I am getting is inside the eclipse folder. I don't know what is happening. Does anyone have any idea abut the problem I am facing.

Basically you shouldn't just use relative filenames within servlets: the servlet container will provide you with mappings for some directory locations, and if you need anything else you should specify that in your servlet parameters.

For example, look at ServletContext.getRealPath .

If you can tell us more about what you're trying to do, that would help.

If it's for reading configuration files you should use the ServletContext.getResourceAsStream(java.lang.String path) , The method will return an InputStream from the resource you have referenced and I advice you keep such files under your WEB-INF folder.

If you want to write files you should always provide (preferably in a configurable location) the absolute path to the directory you need to write in, as well as make sure it exists and has the appropriate permissions for such an operation.

It is because the default working directory of eclipse is the project folder. If u want to write the file in a specified folder using a relative path I suggest you do this:

  1. go to "Run" Menu in eclipse
  2. choose "Run configurations..."
  3. click the "Arguments tab"
  4. Set the working directory below the arguments tab. Choose "Other" and specify a directory.

This means that your project pretends to run in the specified directory.

Hope I helped good luck.

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