繁体   English   中英

Java - 找到 class 的 jar 文件(或类目录)

[英]Java - find jar file of class (or classes directory)

我可以为 jar 文件或类目录请求 URL

Class clazz = ...
URL url = clazz.getProtectionDomain().getCodeSource().getLocation();

但是如何正确地将其转换为File (或Path ) - 特别是对于在 URL 中转义的路径的某些字符? 我试过这个:

String fileName = URLDecoder.decode(url.getFile(), "UTF-8");
File jarFileOrClassesDir = new File(fileName);

但是如果路径中有++被空格替换),这会导致问题。

but this causes problems if there is a + inside the path (the + is replaced with a space).

这是URLDecoder的标准行为。 请参阅 JavaDoc [1] 中的更多信息,其中也提到了 ( + )。

使用Paths的解决方案

使用Paths#get(URI) [2] 应该保留所有“特殊”符号,并且您可以直接传递URI ,该 URI 可以使用URL#toURI() [3] 直接从URL检索。

总而言之:

final var filePath = Paths.get(url.toURI()); // We can extract any information from Path e.g. fileName.

应该按预期工作。


[1] https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/net/URLDecoder.ZFC35FDC70D5FC69D2693EZ5A

[2] https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Paths.html#get(java.net.URI)

[3] https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/net/URL.html#toURI()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM