Srikanth Kandalam
Srikanth Kandalam

Reputation: 1045

How can I create a file in my project folder through Servlet?

My objective is to create file in one of the folders of my Web-App such that when user clicks a download button, it's gonna download the file from that particular folder. For example, my file resides in "MyProjectName/WEB-INF/NewFolder/myfile.xls". Now, how do I create "myfile.xls" in that folder?

Here's what I have already tried:

I have set the file path to "/WEB-INF/NewFolder/" using this code in my Servlet:

   String filePath = getServletContext().getRealPath("/WEB-INF/NewFolder/myfile.xls");

But the problem is, the value of "filePath" in the above code is:

   C:\Users\MyUserName\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\MyProjetName\WEB-INF\NewFolder\myfile.xls

Hence "myfile.xls" is not getting created in "/MyProject/WEB-INF/NewFolder" and getting created in the metadata folder instead. Because of this, it's working only in my machine ie., localhost. When I am trying to access my application through another machine I am not able to download the file. I guess I am passing the absolute path to the JSP page which makes it impossible to download it from a different machine. So could anyone please let me know where I have gone wrong in doing this?

Upvotes: 1

Views: 855

Answers (1)

michael875
michael875

Reputation: 126

Your webapp is deployed to a web server on runtime and filePath points somewhere inside deployment folder not to a project one.

Anyway, why do you want to write into WEB-INF? If you for example redeploy application, then all files inside usually will be removed. Isn't better to use some folder inside server (for example in tomcat we can use ${catalina.home}/myfiles folder or some other outside web server?

Upvotes: 3

Related Questions