2017-07-06 190 views
0

我有一個名爲dog.jpg的文件,它駐留在c:\ Temp中。所以其完整的Windows路徑是C:\ TEMP \ dog.jpg將Windows絕對路徑轉換爲Java

在這個網站每一個答案,建議用/來代替\,但沒有這些語句我想的似乎工作:

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絕對路徑起作用?

感謝您的幫助。

+0

我一直使用Java的類文件,看文件是否存在添加的協議。此外,你的ImageView在哪裏。我也去到該文件所在的文件夾並複製文件資源管理器的地址。然後我添加文件名和擴展名。 – Sedrick

+1

[無法在JavaFX中加載圖像]的可能重複(https://stackoverflow.com/questions/16099427/cannot-load-image-in-javafx) –

+0

看看文檔。 'Image(String)' - 構造器需要一個URL-String!你也可以在你的Stacktrace中看到:'由...引發:java.lang.IllegalArgumentException:無效的URL:未知的協議:c'。您必須使用'file'協議(請參閱Joe C的評論)或打開一個'FileInputStream'並使用構造函數'Image(InputStream)' –

回答

1

圖像類構造函數需要一個URL,而不是絕對路徑,所以在您的網址

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