使用getSystemResource从Servlet访问文件 [英] Using getSystemResource to access files from a servlet

查看:53
本文介绍了使用getSystemResource从Servlet访问文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用getSystemResource从servlet访问文件.这些文件位于项目本身内部和硬盘上.对于我使用的项目中的文件:

I want to access files from a servlet using getSystemResource. These files reside inside the project itself and on the hard disk. For the files inside the project I used:

  ServletContext ctx = getServletContext();
  InputStream is = ctx.getResourceAsStream("/testing.txt");

如果我将文件放在build/web文件夹中,它将起作用,但是当我清理并构建项目时,所有文件都将被删除.我应该把文件放在哪里?

It works if I place the files in build/web folder, but when I clean and build the project all of the files are deleted. Where should I put the files?

对于项目外的文件,我使用File对象:

For files outside the project, I use File object:

 File file = new File("c://tmp//testing.txt");
 InputStream is= new FileInputStream(file); 

这是一个好习惯吗?

推荐答案

除非在应用程序仍在运行的情况下在扩展的WAR中自己创建文件,否则不要删除这些文件.然后,当您重新部署WAR时,确实会删除这些文件,仅仅是因为它们不包含在原始WAR中.

Those files should not be deleted, unless you created them yourself inside the expanded WAR while the app is still running. Then those files will indeed be deleted when you redeploy the WAR, simply because they are not included in the original WAR.

通常的做法是将这些文件存储在webapp上下文外部的固定路径中.您绝对不应该为此使用tmp/temp文件夹.该文件夹可用于基础平台的定期清理.例如使用/var/webapp/upload.正确记录它,以便serveradmin可以事先创建它.如果需要,可以通过某些web.xml参数对其进行配置.

The normal practice is to store those files in a fixed path outside the webapp context. You should definitely not use the tmp/temp folder for this. That folder is eligible for periodic cleanup by the underlying platform. Use for example /var/webapp/upload. Document it properly so that the serveradmin will create it beforehand. Make it if necessary configureable by some web.xml param.

或者当环境不允许创建文件夹和/或写入磁盘时,最后的最好选择是将这些文件存储在SQL数据库中.

Or when the environment disallows creating folders and/or writing to the disk, then your last best bet is storing those files in a SQL database.

这篇关于使用getSystemResource从Servlet访问文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆