[英]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.
应该按预期工作。
[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.