使用文件作为 URLClassLoader 的资源
Using files as resources with URLClassLoader
我正在尝试编写一个 Java 1.7 应用程序,它可以从命令行传递任意文件。该文件将被添加到 ClassLoader,以便它可以用作资源。
将文件添加到 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;
}
}
URLClassLoader
仅支持 jar 文件和文件目录。所以有两种选择:
- 将您的资源放入一个 jar 文件并将该 jar 文件添加到您的
URLClassLoader
。
- 为 class 加载程序提供目录,并使用该目录中文件的相对路径。
我正在尝试编写一个 Java 1.7 应用程序,它可以从命令行传递任意文件。该文件将被添加到 ClassLoader,以便它可以用作资源。
将文件添加到 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;
}
}
URLClassLoader
仅支持 jar 文件和文件目录。所以有两种选择:
- 将您的资源放入一个 jar 文件并将该 jar 文件添加到您的
URLClassLoader
。 - 为 class 加载程序提供目录,并使用该目录中文件的相对路径。