Reading external file from servlet

whenever I read or write a file to a servlet using new File() without using an absolute path, the path I get is inside the eclipse folder. I do not know what's going on. Does anyone have any idea that concerns the problem I am facing.

+4
source share
3 answers

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

For example, see ServletContext.getRealPath .

If you can tell us more about what you are trying to do, this will help.

+2
source

If you must use ServletContext.getResourceAsStream(java.lang.String path) to read configuration files, the method will return an InputStream from the resource you are referencing, and I advise you to store such files in the WEB-INF folder.

If you want to write files, you should always provide (preferably in a custom location) the absolute path to the directory into which you must enter, and also make sure that it exists and has the appropriate permissions for such an operation.

+2
source

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

  • go to the start menu in eclipse
  • select "Run configurations ..."
  • go to the "Arguments" tab
  • Set the working directory under the arguments tab. Select "Other" and specify a directory.

This means that your project claims to be running in the specified directory.

Hope I helped good luck.

0
source

Source: https://habr.com/ru/post/1397734/


All Articles