在servlet(Web应用程序)中,我如何知道相对路径? [英] In servlet (web app) how do I know the relative path?

查看:52
本文介绍了在servlet(Web应用程序)中,我如何知道相对路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在.war文件的根目录中有一个jsp文件.然后我有一个名为STUFF的文件夹.

I have a jsp file in the root of .war file. and then I have a folder named STUFF.

我如何访问STUFF中的文件read.txt?

How do I get access to the file read.txt inside STUFF?

/Name_of_war/STUFF/read.txt是正确的路径吗?

/Name_of_war/STUFF/read.txt is the correct path?

推荐答案

相对于webapp的路径为/STUFF/read.txt .

The webapp-relative path is /STUFF/read.txt.

可以使用

You could use ServletContext#getRealPath() to convert a relative web path to an absolute local disk file system path. This way you can use it further in the usual java.io stuff which actually knows nothing about the web context it is running in. E.g.

String relativeWebPath = "/STUFF/read.txt";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
// Do your thing with File.

但是,如果服务器配置为在内存中而不是磁盘上扩展WAR,则此方法不起作用.使用 getRealPath()总是有这样的警告,不建议在实际应用中使用.如果您最终只需要获取该文件的 InputStream (您可能已使用 FileInputStream ),则最好使用

This however doesn't work if the server is configured to expand the WAR in memory instead of on disk. Using getRealPath() has always this caveat and is not recommended in real world applications. If all you ultimately need is just getting an InputStream of that file, for which you would likely have used FileInputStream, you'd better use ServletContext#getResourceAsStream() to get it directly as InputStream:

String relativeWebPath = "/STUFF/read.txt";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// Do your thing with InputStream.

这篇关于在servlet(Web应用程序)中,我如何知道相对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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