[英]Java Convert Jar URL to File
我正在尝试实现以下目标:从给定的Class
对象,我希望能够检索它所在的文件夹或文件。 这也适用于java.lang.String
类的系统类(它将返回rt.jar
的位置)。 对于“源”类,该方法应返回根文件夹:
- bin
- com
- test
- Test.class
将返回file(com.test.Test.class)
的bin
文件夹的位置。 到目前为止,这是我的实现:
public static File getFileLocation(Class<?> klass)
{
String classLocation = '/' + klass.getName().replace('.', '/') + ".class";
URL url = klass.getResource(classLocation);
String path = url.getPath();
int index = path.lastIndexOf(classLocation);
if (index < 0)
{
return null;
}
// Jar Handling
if (path.charAt(index - 1) == '!')
{
index--;
}
else
{
index++;
}
int index1 = path.lastIndexOf(':', index);
String newPath = path.substring(index1 + 1, index);
System.out.println(url.toExternalForm());
URI uri = URI.create(newPath).normalize();
return new File(uri);
}
但是,此代码失败,因为File(URI)
构造函数抛出IllegalArgumentException
“ URI不是绝对的”。 我已经尝试过使用newPath
来构造文件,但是对于带有空格的目录结构,这是失败的:
- Eclipse Workspace
- MyProgram
- bin
- Test.class
这是由于URL表示使用%20
表示空格,因此文件构造函数无法识别该空格。
是否有一种有效且可靠的方法来获取Java类的(类路径)位置,该方法对目录结构和Jar文件均有效?
请注意,我不需要确切类的确切文件,只需要容器! 我使用此代码查找rt.jar
和语言库,以在编译器中使用它们。
您的代码中的轻微修改应该在这里起作用。 您可以尝试以下代码:
public static File getFileLocation(Class<?> klass)
{
String classLocation = '/' + klass.getName().replace('.', '/') + ".class";
URL url = klass.getResource(classLocation);
String path = url.getPath();
int index = path.lastIndexOf(classLocation);
if (index < 0)
{
return null;
}
String fileCol = "file:";
//add "file:" for local files
if (path.indexOf(fileCol) == -1)
{
path = fileCol + path;
index+=fileCol.length();
}
// Jar Handling
if (path.charAt(index - 1) == '!')
{
index--;
}
else
{
index++;
}
String newPath = path.substring(0, index);
System.out.println(url.toExternalForm());
URI uri = URI.create(newPath).normalize();
return new File(uri);
}
希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.