我试图编写一个Java 1.7应用程序,可以从命令行传递任意文件。该文件将被添加到ClassLoader中,以便它可以被用作资源。使用文件作为URLClassLoader的资源
将该文件添加到URLClassLoader似乎可行,但是如何在添加到ClassLoader后将该文件作为资源获取?
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
public class ClassLoaderTest {
public static void main(String... args) throws MalformedURLException {
File file = new File("/tmp/application.conf");
URLClassLoader classLoader = new URLClassLoader(new URL[]{file.toURI().toURL()});
System.out.println("ClassLoader URLs: " + Arrays.toString(classLoader.getURLs()));
if (file.exists()) {
System.out.println("File \"" + file.getAbsolutePath() + "\" exists!");
} else {
System.out.println("File \"" + file.getAbsolutePath() + "\" does not exist!");
return;
}
URL url = classLoader.getResource(file.getAbsolutePath());
System.out.println("File \"" + file.getAbsolutePath() + "\" as url: " + url);
assert url != null;
}
}
为什么你需要使用ClassLoader?当资源与已知类位于同一目录中时,这很有用,但如果您只是想打开文件并使用它,则不需要使用除URL和文件以外的其他任何内容。 –
@PaulHicks这将被集成到期望从初始化时提供的ClassLoader中检索资源。 –
我注意到你的文件不是jar。 'URLClassLoader'只能用于罐子和罐子目录。您可以将您的conf文件放入jar中,也可以实现自己的类加载器。 –