到目前为止,我所做的是:
/** 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:/我的%20Project /项目%20Name%20Module /../../../../资源/文件/帮助/ 404.html 文件:/ H:/我的%20Project /项目%20Name%20Module /../../../../资源/文件/帮助/ plazaCode.html
通过NetBeans创建的JAR中的文件夹层次结构:
我使用的是Windows 7,JDK 7。
更新
实际上我希望URL
JTextPane
通过方法显示HTML页面:
textPane.setPage(URL url);
我可以有比这更好的解决方案吗?并使用相同的文件夹Heirarchy ..?
答案 0 :(得分:1)
404.html
因为这是一个应用程序资源,它可能最终会嵌入到Jar中。 File
对象访问归档 中的资源 。 URL getURL(String fileName)
为了避免混淆,请将其更改为URL getURL(String resourceName)
。 Class.getResource(String)
,就像之前的问题所讨论的那样。/
来强制它们'绝对',这实际上意味着'从运行时类路径的根目录中查找此资源。 这样String
可能会读取(根据已建议调整其余代码):
private static final String ERROR_404 = "/resources/files/help/404.html";
答案 1 :(得分:1)
您可以使用URL url = getClass().getResource("...")
。可能是“/files/help/404.html”。
答案 2 :(得分:0)
以这种方式创建文件时,您将获得一个相对文件(因此也是相对URL)。要从该路径获取绝对URL,您需要先获取绝对文件。 试试这个:
new File(ERROR_404).getCanonicalFile().toURI().toURL()
(编辑:上面的JTextPane信息之后) 我没有尝试过这个,所以我不知道为什么那不起作用。但这是一个不同的问题,你应该问一个新问题。