【问题标题】:JavaFX File Doesn't Exist Exception Despite File Being In Correct Location尽管文件位于正确的位置,但 JavaFX 文件不存在异常
【发布时间】:2017-03-20 11:08:50
【问题描述】:

正如您在此处看到的,该文件在源文件夹中的项目中明显可用,但是在运行程序时我收到的文件不存在异常。下面我发布了完整的错误:

com.interactivemesh.jfx.importer.ImportException: StlMeshImporter read(File file) : file doesn't exist !
at com.interactivemesh.jfx.importer.stl.StlMeshImporterImpl.read(Unknown Source)
at com.interactivemesh.jfx.importer.stl.StlMeshImporter.read(Unknown Source)
at minimalist.TriangleMeshTest.start(TriangleMeshTest.java:30)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Unknown Source)

【问题讨论】:

标签: file exception javafx import stl


【解决方案1】:

问题是您使用的是绝对路径。如果要使用绝对路径,则需要提供从根目录(/或C:/)开始的完整路径

如果您想使用相对路径 music/untitled.stl,您需要将当前工作目录指向 Test 文件夹。

从代码中加载资源的一种方法是将资源放在src 文件夹内的resource 文件夹中,然后使用getClass().getResourceAsStream("/resource/resource_name")

因此,如果您将音乐文件夹移动到 src 文件夹中,您将能够读取如下文件:

getClass().getResourceAsStream("/music/untitled.stl");

请注意您在开头如何使用“/”。它适用于这种情况,因为 getResourceAsStream 负责使用 ClassLoader 解析到您的 src 目录的路径。

【讨论】:

  • File file = new File(this.getClass().getResource("/music/mapTest3.stl").toExternalForm()); stlImporter.read(file); 我尝试使用它,但是我收到一个空指针异常。您可以在下面提供完整的代码 sn-p 吗?
  • 您是否将音乐文件夹移到了 src 文件夹中?在项目中的极简主义文件夹旁边。我最终使用 this.getClass().getResourceAsStream("/resource/test.txt") 进行了测试,其中资源位于我的 src 文件夹中,并且我得到了一个有效的 Stream。如果您想使用 File 而不是 Stream,请使用 getClass().getResource("/music/mapTest3.stl").getFile());您也可以在这里查看示例:mkyong.com/java/java-read-a-file-from-resources-folder
  • music 是一个资源文件夹,Eclipse 的组织方式在 src 文件夹中没有资源文件夹,而是在它旁边。
  • 通过使用stlImporter.read(new File(System.getProperty("user.dir") + "/music/mapTest3.stl")); 那行设法让它工作,但是我知道当我将它导出到jar 文件时它不会工作。
  • 哦,只需要这样做stlImporter.read(this.getClass().getResource("/mapTest3.stl"));
猜你喜欢
  • 1970-01-01
  • 2015-07-27
  • 2018-12-27
  • 2021-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多