在类加载器的根路径中有一个文件,如何创建它

时间:2011-03-25 10:33:42

标签: java file classloader

File f = new File(path)

在这种情况下如何给出路径参数?

3 个答案:

答案 0 :(得分:2)

你的意思是这样的吗?

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

答案 1 :(得分:1)

原则上,您需要知道类加载器从何处加载其资源。这是依赖类加载器的,大多数类型的类加载器根本不使用文件。如果您有一个URLClassLoader(幸运的是经常),您可以询问它的URL,并查看是否有一个file: URL。然后使用此URL作为基础。

如果您的类加载器没有file:网址,显然您没有机会。

但我认为很可能你做的不对 - 你真的想做什么?

答案 2 :(得分: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