gpt4 book ai didi

java - 将 Windows 绝对路径转换为 ​​Java

转载 作者:行者123 更新时间:2023-12-02 12:40:23 26 4
gpt4 key购买 nike

我有一个名为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 绝对路径起作用?

感谢您的帮助。

最佳答案

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

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

关于java - 将 Windows 绝对路径转换为 ​​Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44959212/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com