Java 在 servlet(Web 应用程序)中,我如何知道相对路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2455474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In servlet (web app) how do I know the relative path?
提问by EugeneP
I have a jsp file in the root of .war file. and then I have a folder named STUFF.
我在 .war 文件的根目录中有一个 jsp 文件。然后我有一个名为 STUFF 的文件夹。
How do I get access to the file read.txt inside STUFF?
如何访问 STUFF 中的 read.txt 文件?
/Name_of_war/STUFF/read.txt is the correct path?
/Name_of_war/STUFF/read.txt 是正确的路径吗?
采纳答案by BalusC
The webapp-relative path is /STUFF/read.txt
.
webapp 相对路径是/STUFF/read.txt
.
You coulduse 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.
您可以使用ServletContext#getRealPath()
将相对 Web 路径转换为绝对本地磁盘文件系统路径。这样你就可以在通常的java.io
东西中进一步使用它,这些东西实际上对它运行的网络上下文一无所知。例如
String relativeWebPath = "/STUFF/read.txt";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
// Do your thing with File.
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
:
但是,如果服务器配置为在内存中而不是在磁盘上扩展 WAR,这将不起作用。使用getRealPath()
总是这个警告,不推荐在现实世界的应用程序中使用。如果您最终需要的只是获取InputStream
该文件的一个,您可能会使用该文件,那么FileInputStream
您最好ServletContext#getResourceAsStream()
直接将其获取为InputStream
:
String relativeWebPath = "/STUFF/read.txt";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// Do your thing with InputStream.
回答by kakacii
If it is located in the classpath, or you can add the folder to the classpath, How about: ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream input = classLoader.getResourceAsStream(fileName);
如果它位于类路径中,或者您可以将文件夹添加到类路径中,如何: ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream input = classLoader.getResourceAsStream(fileName);