创建文件并将其存储在Java Web应用程序文件夹中 [英] Create a file and store in Java web application folder

查看:62
本文介绍了创建文件并将其存储在Java Web应用程序文件夹中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个xml文件并将其存储在spring Mvc Web应用程序内的文件夹中.

I would like to create an xml file and store in a folder within my spring Mvc web application.

我可以使用 request.getContextPath()

但是

如何获取应用程序的相对路径,以便它可以在任何计算机上独立于应用程序文件夹的位置使用?

how do i get the application's relative path so it will work on any machine indipendently by the location of the application's folder?

C:/folder/folder/MYAPPLICATIONROOTFOLDER

推荐答案

您要执行此操作.

首先,您需要获取ServletContext.我不知道如何在Spring MVC中完成此操作,但是它在某处.

First, you need to get the ServletContext. I don't know how this is done in Spring MVC, but it's there somewhere.

然后您可以执行以下操作:

Then you can do:

ServletContext ctx = getServletContextFromSpringSomehow();
String path = ctx.getRealPath("/folder/filename.txt");
FileWriter fw = new FileWriter(path);

此处的键是ServletContext.getRealPath.它为您提供了Webapp内部资源的本地文件系统路径.观察者在这里使用"/",因为它是一个URL,而不是文件名.容器将为您提供有效的文件名.请注意,这仅在您的容器爆炸WAR或部署爆炸WAR时有效.如果WAR没有爆炸,您将从容器中得到一个空值.

The key here is ServletContext.getRealPath. It gives you the local file system path of a resource from within your webapp. Observer that you use "/" here, as it's a URL, not a file name. The container will give you a valid file name in return. Note, this only works if your container explodes your WAR, or you deploy an exploded WAR. If the WAR is NOT exploded, you will get a null back from the container.

还请注意,这将适用于不存在的文件.容器不检查文件的实际存在.但这实际上取决于您创建任何缺少的中间目录等.

Also note, this WILL work for non-existent files. The container does not check for the actual existence of the file. But it will be up to you to actually create any missing intermediate directories, etc.

最后,当然,即使您返回了文件路径,也并不意味着您实际上可以写入该路径.这是超出容器范围的操作系统许可问题.

Finally, of course, that even if you get a file path back, doesn't mean you can actually write to that path. That's a OS permission issue outside of the scope of the container.

这篇关于创建文件并将其存储在Java Web应用程序文件夹中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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