加载动态创建的资源文件:Java
Load Dynamically Created Resource File: Java
我正在资源文件中使用动态名称动态创建一堆属性文件,为此我使用以下代码
File file = new File("src/main/resources/" + fileName+ ".properties");
FileOutputStream fileOut = new FileOutputStream(file);
properties.store(fileOut, fileName);
fileOut.close();
问题:- 每次我都必须手动刷新资源文件才能访问动态创建的属性文件。我该如何解决这个问题?
我通过将资源文件存储在 class 路径中解决了这个问题,这样 class 加载程序就可以加载动态添加的文件。
public static void addResourceURLIntoClassPath(URL u) throws IOException {
URLClassLoader urlLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class<URLClassLoader> sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL", new Class[] { URL.class });
method.setAccessible(true);
method.invoke(urlLoader, new Object[] { u });
} catch (Throwable t) {
t.printStackTrace();
}
}
这里URL是src/main/resources
的路径
更好的解决方案是使用 apache-commons 配置项目。它提供了更清洁和经过测试的 api。这是关于如何使用它的 link。
我正在资源文件中使用动态名称动态创建一堆属性文件,为此我使用以下代码
File file = new File("src/main/resources/" + fileName+ ".properties");
FileOutputStream fileOut = new FileOutputStream(file);
properties.store(fileOut, fileName);
fileOut.close();
问题:- 每次我都必须手动刷新资源文件才能访问动态创建的属性文件。我该如何解决这个问题?
我通过将资源文件存储在 class 路径中解决了这个问题,这样 class 加载程序就可以加载动态添加的文件。
public static void addResourceURLIntoClassPath(URL u) throws IOException {
URLClassLoader urlLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class<URLClassLoader> sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL", new Class[] { URL.class });
method.setAccessible(true);
method.invoke(urlLoader, new Object[] { u });
} catch (Throwable t) {
t.printStackTrace();
}
}
这里URL是src/main/resources
的路径更好的解决方案是使用 apache-commons 配置项目。它提供了更清洁和经过测试的 api。这是关于如何使用它的 link。