java 获取Java中“网页内容”文件夹的绝对路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27201137/
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
Get absolute path of "web content" folder in Java
提问by Anh Nguyen
I want to get the absolute path of Web content
folder in source code so I can retrieve another folder to upload file.
我想Web content
在源代码中获取文件夹的绝对路径,以便我可以检索另一个文件夹来上传文件。
I tried ServletActionContext.getServletContext().getRealPath("images")
to get the folder image in source code.
我试图ServletActionContext.getServletContext().getRealPath("images")
在源代码中获取文件夹图像。
Expected result should be:
预期结果应该是:
"C:\Learning\Workspace\Eclipse\boxingsaigon\WebContent\images".
“C:\Learning\Workspace\Eclipse\boxingsaigon\WebContent\images”。
But it returns me where the web was deployed:
但它返回了我部署网络的位置:
Actual result is:
实际结果是:
"C:\Learning\Workspace\Eclipse.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\boxingsaigon\images".
“C:\Learning\Workspace\Eclipse.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\boxingsaigon\images”。
Is there any way to do this?
有没有办法做到这一点?
回答by Yagnesh Agola
Your approach to get absolute path is right. You can get the full path by
您获取绝对路径的方法是正确的。您可以通过以下方式获取完整路径
ServletActionContext.getServletContext().getRealPath("images");
but you get path C:\Learning\Workspace\Eclipse.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\boxingsaigon\images
is the path where your actual web application is deployed.
但是您得到的路径C:\Learning\Workspace\Eclipse.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\boxingsaigon\images
是部署实际 Web 应用程序的路径。
If you change the deployed path to tomcat webapps directory that it gives you path to that directory.
you can to get the path where your actual source code is reside.
如果您将部署路径更改为 tomcat webapps 目录,它会为您提供该目录的路径。
您可以获取实际源代码所在的路径。
ServletContext.getRealPath() returns the absolute file path on the server's
filesystem would be served by a request for
"http://host/contextPath/index.html", where contextPath is the
context path of this ServletContext..
回答by techGaurdian
You can try using this:
你可以尝试使用这个:
public String getRealFile(HttpServletRequest request, String path) {
return request.getSession().getServletContext().getRealPath(path);
}
Hope this helps.
希望这可以帮助。