如何修复javax.imageio.IIOException:Can';无法在Linux上读取输入文件

如何修复javax.imageio.IIOException:Can';无法在Linux上读取输入文件,java,embedded-resource,Java,Embedded Resource,我正在开发一个小型Gui应用程序,希望从资源文件夹加载我的图像。这在Windows上确实有效,但在Linux(Ubuntu19.04和RaspbianBuster)上则不行 我一直在试着从 getClass().getResource("black.jpg").getFile() 到 这是我的视图类,从JFrame(短路)扩展而来 终端中的错误消息: javax.imageio.IIOException: Can't read input file! at java.desktop/j

我正在开发一个小型Gui应用程序,希望从资源文件夹加载我的图像。这在Windows上确实有效,但在Linux(Ubuntu19.04和RaspbianBuster)上则不行

我一直在试着从

getClass().getResource("black.jpg").getFile()

这是我的视图类,从JFrame(短路)扩展而来

终端中的错误消息:

javax.imageio.IIOException: Can't read input file!
    at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
    at de.grapatin.escaperoom.view.View.<init>(View.java:38)
    at de.grapatin.escaperoom.controller.Controller.<init
(Controller.java:11)
    at de.grapatin.escaperoom.App.main(App.java:11)
产量

System.out.println(getClass().getResource("/black.jpg").getFile());

这个!不是从我这边来的

我刚刚发现Windows也不会从jar中读取图像文件。但它在文件夹的根目录中

这个问题不是以下问题的重复:因为在我的情况下,接受的答案不起作用,语法完全不同,与我的问题中接受的答案相反。此外,编辑没有清楚地显示如何调整解决方案。

不要使用URL的getFile()方法。它不返回有效的文件名。它实际上返回URL的路径部分,所有百分比转义都保持不变。它之所以命名为getFile,是因为URL类是Java 1.0的一部分,Java 1.0是在90年代中期发布的,当时几乎所有URL都引用物理文件,无论是在同一台计算机上还是在不同的计算机上

幸运的是,你不需要它。您只需使用:


将资源视为URL而不是文件的一个重要好处是,当您将程序打包到.jar文件中时,代码可以正常工作。

可能只是猜测,因为它无法找到您应该使用的映像
getClass().getResource(“/images/yourmagename.extension”)。我对此深表怀疑,因为它能够在Windows 10 Pro x64中找到图像。当然,如果对子文件夹执行此操作有任何区别,我会尝试,但我认为不会有任何区别。正如预期的那样,bI=ImageIO.read(新文件(getClass().getClassLoader().getResource(“images/black.jpg”).getFile())会出现相同的错误消息;对于
getClass()。你能用你的项目结构更新你的问题吗!可能重复的
javax.imageio.IIOException: Can't read input file!
    at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
    at de.grapatin.escaperoom.view.View.<init>(View.java:38)
    at de.grapatin.escaperoom.controller.Controller.<init
(Controller.java:11)
    at de.grapatin.escaperoom.App.main(App.java:11)
─src
│   ├───main
│   │   ├───java
│   │   │   └───de
│   │   │       └───marvin
│   │   │           └───uitest
│   │   │               ├───controller
│   │   │               ├───model
│   │   │               │   └───enums
│   │   │               ├───util
│   │   │               └───view
│   │   └───resources
│   │       └───images
System.out.println(getClass().getResource("/black.jpg").getFile());
file:/C:/Users/marvin/uitest/target/uitest-0.0.1-SNAPSHOT.jar!/black.jpg
bI = ImageIO.read(getClass().getResource("/images/black.jpg"));