将 Windows 绝对路径转换为 Java



我有一个名为dog.jpg的文件,它驻留在c:\Temp中。所以它的完整 Windows 路径是 C:\Temp\dog.jpg

这个网站上的每个答案都建议用/替换 \,但我尝试的这些陈述似乎都不起作用:

Image image = new Image("C:\Temp\dog.jpg");
Image image = new Image("C://Temp//dog.jpg");
Image image = new Image("C:/Temp/dog.jpg");

(顺便说一句,如果我将 dog.jpg 放在当前工作目录中并使用:

Image image = new Image("dog.jpg");

(

我收到以下异常报告:

Exception in Application start method
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: Invalid URL: unknown protocol: c
at javafx.scene.image.Image.validateUrl(Image.java:1121)
at javafx.scene.image.Image.<init>(Image.java:620)
at Inclass_week7_session_1_4.start(Inclass_week7_session_1_4.java:21)
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)
... 1 more
Caused by: java.net.MalformedURLException: unknown protocol: c
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at javafx.scene.image.Image.validateUrl(Image.java:1115)


C:JavaTutorialJavaFX 2>javac -version
javac 1.8.0_102

我做错了什么?我怎样才能让这个 Windows 绝对路径工作?

感谢您的帮助。

图像类构造函数需要 url 而不是绝对路径,因此请在 url 中添加协议

Image img = new Image("file:///C:/Temp/dog.jpg");

相关内容

  • 没有找到相关文章

最新更新