【问题标题】:Load Dynamically Created Resource File: Java加载动态创建的资源文件:Java
【发布时间】:2017-04-26 09:59:19
【问题描述】:

我正在使用资源文件中的动态名称动态创建一堆属性文件,为此我使用以下代码

File file = new File("src/main/resources/" + fileName+ ".properties");
FileOutputStream fileOut = new FileOutputStream(file);
properties.store(fileOut, fileName);
fileOut.close();

问题:- 每次我都必须手动刷新资源文件才能访问动态创建的属性文件。我该如何解决这个问题?

【问题讨论】:

  • 为什么不将文件创建到外部路径并从那里使用它们?

标签: java properties-file


【解决方案1】:

我通过将资源文件存储在类路径中来解决这个问题,以便类加载器可以加载动态添加的文件。

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的路径

【讨论】:

  • 非常感谢,它正在工作。!我使用addResourceURLIntoClassPath(new File("/Users/pratik/Documents/Projects/RobotSampleTest/com.automation/src/test/resources").toURI().toURL()); 调用了这个方法
【解决方案2】:

更好的解决方案是使用 apache-commons 配置项目。它提供了更干净且经过测试的 API。这里是link如何使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 2010-11-13
    • 2011-03-19
    • 1970-01-01
    相关资源
    最近更新 更多