2011-03-25 24 views

回答

2

你的意思是這樣的嗎?

URL resource = Thread.currentThread().getContextClassLoader().getResource("config.properties"); 
    File f = new File(resource.toURI()); 
1

原則上,您需要知道類加載器從何處加載其資源。這是依賴於類加載器的,大多數類加載器根本不使用文件。如果你有一個URLClassLoader(幸運的話很常見),你可以詢問它的URL,看看是否有一個file: URL。然後使用這個URL作爲基礎。

如果你的類加載器沒有file:的URL,顯然你沒有機會。

但我認爲你很可能沒有做正確的事 - 你真的想做什麼?

1

你可以使用更好的選項,並去java.net.URLClassLoader

該類加載器用於從指向JAR文件和目錄的URL的搜索路徑加載類和資源。

A URLClassLoader可用於加載任何目錄中的類。

退房this example

// Create a File object on the root of the directory containing the class file 
File file = new File("c:\\myclasses\\"); 

try { 
    // Convert File to a URL 
    URL url = file.toURL();   // file:/c:/myclasses/ 
    URL[] urls = new URL[]{url}; 

    // Create a new class loader with the directory 
    ClassLoader cl = new URLClassLoader(urls); 

    // Load in the class; MyClass.class should be located in 
    // the directory file:/c:/myclasses/com/mycompany 
    Class cls = cl.loadClass("com.mycompany.MyClass"); 
} catch (MalformedURLException e) { 
} catch (ClassNotFoundException e) { 
} 

而且,看看File ClassLoader in Java