如何从jar下的相对路径获取URL? [英] How can I get a URL from relative path under a jar?
问题描述
到目前为止,我所做的是:
What I have done so far is :
/** Default location of help files folder */
private static final String DEFAULT_PATH = "../../../../resources/files/help/";
/** A 404 error file */
private static final String ERROR_404 = "../../../../resources/files/help/404.html";
/**
* @param fileName
* @return The URL of file, if found at default location, otherwise a 404 error page URL.
*/
public static URL getURL(String fileName) throws MalformedURLException{
URL url = (new File(ERROR_404)).toURI().toURL();
System.out.println(url);
url = (new File(DEFAULT_PATH + fileName)).toURI().toURL();
System.out.println(url);
return url;
}
输出:
文件:/H:/My%20Project/Project%20Name%20Module/../../../../resources/files/help/404.html 文件:/H:/My%20Project/Project%20Name%20Module/../../../../resources/files/help/plazaCode.html
file:/H:/My%20Project/Project%20Name%20Module/../../../../resources/files/help/404.html file:/H:/My%20Project/Project%20Name%20Module/../../../../resources/files/help/plazaCode.html
通过NetBeans创建的JAR中的文件夹层次结构:
Folder Hierarchy in the JAR created through NetBeans:
我在Windows 7,JDK 7上.
I am on Windows 7, JDK 7.
更新:
实际上,我希望此URL
表示JTextPane
通过方法显示HTML页面:
Actually I want this URL
for a JTextPane
to show a HTML page by method:
textPane.setPage(URL url);
有什么比这更好的解决方案了吗?并具有相同的文件夹层次结构.
Can I have any better solution than this? and with the same Folder Heirarchy.. ?
推荐答案
-
404.html
,因为这是一个应用程序资源,所以它最终可能会嵌入到Jar中. - 无法使用
File
对象访问存档 中的资源. -
URL getURL(String fileName)
为避免混淆,请将其更改为URL getURL(String resourceName)
. - 使用
Class.getResource(String)
的方式与您之前的问题所讨论的方式相同. - 相对" URL到那时会变得很危险,因为它们依赖于调用它们的类的程序包,所以我通常通过在整个路径前加上一个单独的
/
作为前缀来使它们成为绝对",这实际上意味着寻找"该资源来自运行时类路径的根".
404.html
since this is an application resource, it will probably end up embedded in a Jar.- Resources in archives cannot be accessed using a
File
object. URL getURL(String fileName)
To help avoid confusion, change that toURL getURL(String resourceName)
.- Use
Class.getResource(String)
much as discussed on your previous questions. - 'Relative' URLs become dangerous by that stage, since they depend on the package of the class that calls them, I generally make them 'absolute' by prefixing the entire path with a single
/
which effectively means 'look for this resource, from the root of the run-time class-path'.
以便String
可以读取(按照已经建议的方式调整其余代码):
So that String
might read (adjusting the rest of the code as already advised):
private static final String ERROR_404 = "/resources/files/help/404.html";
这篇关于如何从jar下的相对路径获取URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!