2011-03-25 2 views

答えて

2

このような意味ですか?

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

原則として、クラスローダーがそのリソースをロードする場所から知る必要があります。これはクラスローダに依存し、ほとんどのタイプのクラスローダはファイルをまったく使用しません。 URLClassLoaderを持っている場合(幸いにも頻繁に)、URLについて質問し、file:というURLが1つあるかどうかを調べることができます。次に、このURLをベースとして使用します。

クラスローダーにfile:のURLがない場合、明らかにあなたはチャンスがありません。

しかし、おそらくあなたは正しいことをしていないと思います。あなたは本当に何をしたいのですか?

1

より良いオプションを使用してjava.net.URLClassLoaderに行くことができます。

このクラスローダーは、JARファイルとディレクトリの両方を参照するURLの検索パスからクラスとリソースをロードするために使用されます。

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

関連する問題