0

(刚开始学习)

Java 程序使用类加载器 getResourceAsStream 函数从类路径中读取属性文件。该程序在eclipse中运行没有错误。执行从 distZip gradle 任务生成的批处理文件会导致以下错误

Exception in thread "main" java.io.FileNotFoundException: property file 'prop.properties' not found in the classpath
    at com.foo.bar.fb.utility.PropResourceCache.getProperties(PropResourceCache.java:26)
    at com.foo.bar.fb.offline.RunOfflineProcess.main(RunOfflineProcess.java:40) Press any key to continue . . .

我认为这是由于清单文件中未包含属性。有没有办法在程序的 src/main/resources/Properties 目录中包含所有属性文件?最佳做法是什么?

gradle 构建入口

jar.doFirst{
        manifest {
            attributes(
                "Manifest-Version"    : "1.0",
                "Built-By"            : System.getProperty('user.name'),
                "Built-Date"          : new Date(),
                "Main-Class"          : mainClassName,
                "Class-Path"          : configurations.runtime.collect{ "lib/"+it.getName() }.join(' ') 
            )
        }
}

访问属性文件

    public Properties getProperties(String propFileName) throws IOException {
    String name = File.pathSeparator+"Properties"+File.separator+propFileName;
    Properties props = new Properties();
    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(name);

    if (inputStream == null) {
        throw new FileNotFoundException("property file '" + name
            + "' not found in the classpath");
    }
    props.load(inputStream);

    return props;
}
4

1 回答 1

3

Everything under src/main/resources (not src/main/resource) is automatically included in the Jar. You can verify this by unpacking the Jar.

于 2013-07-29T16:59:16.010 回答