new File(path).toURI().toURL();
使用 Java 11:
Path.of(string).toUri();
使用 Java 7:
Paths.get(string).toUri();
要转换为老式 URL 类(为什么?),请添加 .toURL()
。请注意,字符串输出存在差异。现代的 URI::toString
以 file:///
(传统的 URL 语法)开头,而几乎弃用的 URL::toString
以 file:/
(现代的 URI 语法)开头。奇怪🤷
java.nio.file.Paths
。另外,请务必明确您的意思是“URI vs URL”中的实现。 Anway java.net.URL.toString()
在 Unix 上产生同样的东西,因为它必须。它只显示一个非常错误的“/”(参见file URI scheme)。我猜这是在 Java 中的原因,最好使用 java.net.URI
。它在调用 .toString()
时正确生成“file://[host]/”。
new File("path_to_file").toURI().toURL();
new URL("file:///your/file/here")
/your/file/here
是 Unix/Linux 上文件的绝对路径。我认为在 Windows 上会有所不同。
new URL("file:my.properties");
file:///C:\\file.zip
File myFile=new File("/tmp/myfile");
URL myUrl = myFile.toURI().toURL();
在这里查看完整的语法:http://en.wikipedia.org/wiki/File_URI_scheme 对于类似 unix 的系统,它将是 @Alex 所说的 file:///your/file/here
而对于 Windows 系统是 file:///c|/path/to/file
File.toURI().toURL()
是要走的路
.properties
文件中时。
java file url
时会出现此问题/答案,在我的情况下,这意味着我正在搜索 file://
URL 的格式,在 Java 中,用于 .properties
文件,或者手动输入等
file://
是必要的。依赖于系统并不是一个大问题,因为它是一个可变属性。
你也可以使用
[AnyClass].class.getResource(filePath)
jar:file:/home/user/a/b/c/foo.jar!/com/example/stuff/config.txt
。
我在 Linux 上使用 Java 进行了尝试。以下可能性是可以的:
file:///home/userId/aaaa.html
file:/home/userId/aaaa.html
file:aaaa.html (if current directory is /home/userId)
不工作是:
file://aaaa.html