简体   繁体   English

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

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

I can request the URL for the jar file or classes directory where Java loaded a class from:我可以为 jar 文件或类目录请求 URL

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

but how to correctly convert this to a File (or Path ) - especially with respect to some characters of the path escaped in URLs?但是如何正确地将其转换为File (或Path ) - 特别是对于在 URL 中转义的路径的某些字符? I've tried this:我试过这个:

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).但是如果路径中有++被空格替换),这会导致问题。

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

This is standar behavior of URLDecoder .这是URLDecoder的标准行为。 See more information at JavaDoc [1], plus ( + ) is mentioned there as well.请参阅 JavaDoc [1] 中的更多信息,其中也提到了 ( + )。

Solution using Paths使用Paths的解决方案

Using Paths#get(URI) [2] should preserve all "special" symbols and you can pass directly URI which can be retrieved directly from URL using URL#toURI() [3].使用Paths#get(URI) [2] 应该保留所有“特殊”符号,并且您可以直接传递URI ,该 URI 可以使用URL#toURI() [3] 直接从URL检索。

So in summary:总而言之:

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

shoud work as expected.应该按预期工作。


[1] https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/net/URLDecoder.html [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) [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() [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