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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:23:29  来源:igfitidea点击:

Get absolute path of "web content" folder in Java

javajspservletsabsolute-path

提问by Anh Nguyen

I want to get the absolute path of Web contentfolder 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\imagesis 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 目录,它会为您提供该目录的路径。
您可以获取实际源代码所在的路径。

From Doc

来自文档

 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.

希望这可以帮助。