将Windows绝对路径转换为Java

时间:2017-07-06 21:32:07

标签: java windows path absolute translate

我有一个名为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:\Java\Tutorial\JavaFX 2>javac -version
javac 1.8.0_102

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

图像类构造函数需要一个url而不是一个绝对路径,所以在你的url中添加协议

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