create temp files in tomcat webapps folder

2019-07-24 06:31发布

问题:

I have a Google Web Project which works perfect on Development mode. Somewhere inside this project, I create some .xml files which I delete after parsing.

When I deploy the .war file of my project in Tomcat7 (var/lib/tomcat7/webapps) (I use the tomcat manage to deploy it) the project fails to create any file. I've tried all possible paths inside the webapps folder. I even tried context.getRealPath("/")+"/ROOT/tmp/" but nothing happens

回答1:

You should be using the temp folder instead of attempting to write directly to your webapp's deployment directory:

ServletContext app = (servlet).getServletContext();
File tmpDir = (File)app.getAttribute("javax.servlet.context.tempdir");
File targetFile = new File(tmpDir, "mytempfile.xml");
...

Remember to do everything in a try/catch block and properly clean-up your resources in the 'finally' block or you'll be sorry ;)