在 tomcat 中创建目录并从中读取
我需要创建目录并在 servlet 中读取它们。
如果我想在 webapps/appName
目录中创建一个文件夹,我应该怎么做才能实现这一目标?
目前如果我这样做:
File file = new File("conf\Conf.xml");
这将查看目录“{TOMCAT_HOME}\bin\”
如何将我的默认目录指向“{TOMCAT_HOME}\webapps\appName\”
I need to create directories and read from them in a servlet.
If I wanted to create a folder in my webapps/appName
directory, what should I do to achieve this?
Currently if I do:
File file = new File("conf\Conf.xml");
This will look into the directory "{TOMCAT_HOME}\bin\"
How do I point my default directory to "{TOMCAT_HOME}\webapps\appName\"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
什么也没有。您应该忘记这种方法并寻找替代方法。每当您重新部署 WAR 甚至重新启动服务器时,在 webapp 文件夹结构中所做的所有更改都将不可逆转地丢失。
您需要准备一个具有读/写权限的固定文件夹,并将其绝对磁盘文件系统路径设置为配置设置(properties/xml 文件)或虚拟机参数。例如,
/var/webapp/uploads
。这样您就可以按照通常的方式使用File
。一个完全不同的替代方案是使用数据库。如果您将 Web 应用程序部署到不允许您在 Web 应用程序上下文之外创建文件夹的主机,这将是唯一的选择。
Nothing. You should forget about this approach and look for an alternative approach. Whenever you redeploy the WAR or even whenever you restart the server, all changes made in the webapp folder structure will irreversibly get lost.
You need to prepare a fixed folder with read/write rights and set its absolute disk file system path as a configuration setting (properties/xml file) or as a VM argument. For example,
/var/webapp/uploads
. This way you can just use theFile
the usual way.A completely different alternative is to use a database. This would be the only alternative if you are deploying your web application to a host which does not allow you to create folders outside the webapp context.
为什么要这样做的问题放在一边......最可移植的方法是将
添加到您的 servlet 并以这种方式传递路径。您还可以使用 System.getenv() 来获取 TOMCAT_HOME 环境变量(假设已设置)。
Questions of why you'd do this aside.... The most portable way would be to add an
<init-param>
to your servlet and pass the path in that way.You could also use
System.getenv()
to get theTOMCAT_HOME
environment variable, assuming it has been set.您只需要从 servlet 上下文中获取真实路径,该路径将提供您正在查找的路径,执行类似的操作,此代码将创建以当前日期作为名称的目录。如果您想避免 servlet 启动延迟,请创建一个线程并将目录创建委托给该线程。您可以像这样将目录路径保存到 servlet 上下文。
You just need to get real path from servlet context that would give the path you are looking for , do some thing like this, this code will create directory with current date as name. If you want avoid delay in servlet start up create a thread and delegate the directory creation to the thread. You can save the directory path to servlet context like this.