[英]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.