【问题标题】:Java - Uber jar (Maven Shaded) cannot see resource as a URLJava - Uber jar (Maven Shaded) 无法将资源视为 URL
【发布时间】:2019-12-23 03:52:20
【问题描述】:

我有一个胖 uber jar(使用 Maven Shade 完成),其中包含以下内容:

FATTY-UBER-FATTY
\- mainAppPackage
   +- some.class.file
\- otherdep
   +- some.other.dep.class
someprop.properties
logging.properties
\- META-INF
   - MANIFEST.MF

我尝试使用Paths.get(fileObject.getPath()) 并得到以下异常

Exception in thread "main" java.nio.file.InvalidPathException: Illegal char <:> at index 4: file:\C:\projectdir\target\projectdir-0.0.1-SNAPSHOT-shaded.jar!\logging.properties
        at sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182)
        at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
        at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
        at sun.nio.fs.WindowsPath.parse(WindowsPath.java:94)
        at sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:255)
        at java.nio.file.Paths.get(Paths.java:84)
        at mainAppPackage.main.app.MainApp.main(MainApp.java:32)

但是,当我尝试使用 getResourceAsStream() 并获取输入时,我可以读取文件!那么 URL 有什么问题呢?是否与访问资源的权限有关?

【问题讨论】:

  • 向我们展示您的代码。
  • Path 为您提供文件系统上的路径。如果您想在 jar 中使用文件,请使用 InputStream 或 getResourceAsStream()。
  • @michalk 正是我的想法:(。感谢您指出这一点。

标签: java url inputstream maven-shade-plugin uberjar


【解决方案1】:

https://docs.oracle.com/javase/8/docs/technotes/guides/lang/resources.html

我认为总结是

1) CLassloader 不能执行特权操作,例如访问 jar 上下文之外的文件信息。因此,永远不可能通过暴露绝对路径的 URL 进行访问。

2) 使用相对路径,资源将始终是 jar 的“相对”。因此,该项目是可见的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 2020-07-06
    相关资源
    最近更新 更多