且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从jar下的相对路径获取URL?

更新时间:2023-09-19 13:06:28

  1. 404.html,因为这是一个应用程序资源,所以它最终可能会嵌入到Jar中.
  2. 无法使用File对象访问存档 中的资源.
  3. URL getURL(String fileName)为避免混淆,请将其更改为URL getURL(String resourceName).
  4. 使用Class.getResource(String)的方式与您之前的问题所讨论的方式相同.
  5. 相对" URL到那时会变得很危险,因为它们依赖于调用它们的类的程序包,所以我通常通过在整个路径前加上一个单独的/作为前缀来使它们成为绝对",这实际上意味着寻找"该资源来自运行时类路径的根".
  1. 404.html since this is an application resource, it will probably end up embedded in a Jar.
  2. Resources in archives cannot be accessed using a File object.
  3. URL getURL(String fileName) To help avoid confusion, change that to URL getURL(String resourceName).
  4. Use Class.getResource(String) much as discussed on your previous questions.
  5. '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";