java 在java中获取url的绝对路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5881277/
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-10-30 13:15:57  来源:igfitidea点击:

Get Absolute path of a url in java

javatomcat

提问by Ria

Is there a way to retrieve the absolute path of url (http://localhost:8080/myApp) in java. The scenario is, i need to connect to csv file located in tomcat server. The statement works well if I enter the absolute path, but is there a solution to retrieve url's path using getAbsolutePath().Sorry if I'm wrong.

有没有办法在java中检索url的绝对路径(http://localhost:8080/myApp)。场景是,我需要连接到位于 tomcat 服务器中的 csv 文件。如果我输入绝对路径,则该语句运行良好,但是否有使用 getAbsolutePath() 检索 url 路径的解决方案。对不起,如果我错了。

Connection conn = DriverManager(getConnection("jdbc:relique:csv:/home/apache-tomcat-6.0.26/webapps/myApp/"))

Thanks in advance.

提前致谢。

回答by Joachim Sauer

You can use ServletContext.getRealPath(), which does exactly what you want.

您可以使用ServletContext.getRealPath(),这正是您想要的。

Note that it does notnecessarily work in all situations. For example, if your Tomcat is configured to deploy the .war file without unpacking it, then this will return null.

注意,它并没有一定适用于所有情况。例如,如果您的 Tomcat 配置为部署 .war 文件而不解压它,那么这将返回 .war 文件null

回答by Mayank

I don't know much about JAVA.

我对JAVA知之甚少。

May be getServletContext().getContextPath() is something you are looking for

May be getServletContext().getContextPath() is something you are looking for

EDIT:
Or may be getRealPath()

编辑:
Or may be getRealPath()

回答by Andreas Dolk

Tomcat is not a http server. All tomcat urlsreference services, not files.

Tomcat 不是 http 服务器。所有tomcat url参考服务,而不是文件。

You'll have to implement another service that sends the csv file on request, if you want to get it through any http URL. URL's like http://localhost/myapp/input.csvrequire a http server like apache httpd.

如果您想通过任何 http URL 获取 csv 文件,则必须实施另一项根据请求发送 csv 文件的服务。URL 之类的http://localhost/myapp/input.csv需要像 apache httpd这样的 http 服务器。

(Hope I got your question correct...)

(希望我答对了你的问题...)