加载动态创建的资源文件:Java
我在资源文件中使用动态名称动态创建了一组属性文件,为此我使用以下代码加载动态创建的资源文件:Java,java,properties-file,Java,Properties File,我在资源文件中使用动态名称动态创建了一组属性文件,为此我使用以下代码 File file = new File("src/main/resources/" + fileName+ ".properties"); FileOutputStream fileOut = new FileOutputStream(file); properties.store(fileOut, fileName); fileOut.close(); 问题:-每次我都必须手动刷新资源文件以访问动态创建的属性文件。如何解
File file = new File("src/main/resources/" + fileName+ ".properties");
FileOutputStream fileOut = new FileOutputStream(file);
properties.store(fileOut, fileName);
fileOut.close();
问题:-每次我都必须手动刷新资源文件以访问动态创建的属性文件。如何解决此问题?我通过将资源文件存储在类路径中,以便类加载器可以加载动态添加的文件来解决此问题
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();
}
}
公共静态void addResourceURLIntoClassPath(URL u)引发IOException{
URLClassLoader urlLoader=(URLClassLoader)ClassLoader.getSystemClassLoader();
类sysclass=URLClassLoader.Class;
试一试{
方法Method=sysclass.getDeclaredMethod(“addURL”,新类[]{URL.Class});
方法setAccessible(true);
调用(urlLoader,新对象[]{u});
}捕获(可丢弃的t){
t、 printStackTrace();
}
}
这里URL是src/main/resources的路径更好的解决方案是使用apachecommons配置项目。它提供了更干净、经过测试的API。下面是有关如何使用它的详细信息。为什么不将文件创建到外部路径并从那里使用它们呢?非常感谢,它正在工作。!我使用
addResourceURLIntoClassPath(新文件(“/Users/pratik/Documents/Projects/RobotSampleTest/com.automation/src/test/resources”).toURI().toURL()调用了这个方法代码>