【问题标题】:How to access property resource file in Android to parse Maven project information?如何访问Android中的属性资源文件来解析Maven项目信息?
【发布时间】:2012-12-24 13:14:41
【问题描述】:

在我的(非 Android 测试)测试中,我将 src/main/resources 中名为 common.properties 的资源放入我的 Android 项目中,以从中读取 Maven 项目版本它:

@Test
public void testReadVersion() throws IOException {      
    Properties props = new Properties();
    props.load(FileUtils.openInputStream(FileUtils.toFile(this.getClass().getResource("/common.properties"))));

    String version = props.getProperty("version");

    assertNotNull(version);
    assertTrue(!"".equals(version));
}

这行得通。 但是当我尝试在生产代码中访问相同的资源时,访问资源时总是得到 NullPointerExceptions:

    Properties props = new Properties();
    final StringBuilder versionBuilder = new StringBuilder();

    try {
        props.load(FileUtils.openInputStream(FileUtils.toFile(this.getClass().getResource("/common.properties"))));

        versionBuilder.append(props.getProperty("version"));
    } 
    catch (IOException e) {
        // will be ignored.
    }

我调试了它。它是空的,因为它没有找到资源。我应该如何解决这个问题?当我将文件放入 res/raw 以供

读取时
props.load(getResources().openRawResource(R.raw.common));

文件访问有效,但无法转换我的文件内容中的值:version=${project.version}。 结果将是值字符串本身 ${project.version} 而不是 Version 1.0 或其他东西。我有哪些选择?

[更新]
下面接受的解决方案不再适用于我的最新项目。我总是得到 ${project.version} 而不是价值。不知道为什么会这样。甚至 AssetManager 的解决方案都不适合我。我找到了一个很好的解决方法,它也不太方便。我获取并显示 android:versionName (AndroidManifest) 的信息。

String versionName = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;

TextView version = (TextView)findViewById(R.id.version);
version.setText(" " + versionName);

【问题讨论】:

    标签: android maven resources classpath


    【解决方案1】:

    首先我建议使用更简单的方法:

    InputStream resourceAsStream = this.getClass().getResourceAsStream("/common.properties");
    Properties prop = new Properties();
    prop.load(resourceAsStream);
    

    如果您在测试或生产代码中运行,这将起作用。 此外,要从资源中替换的 pom 中获取值,您必须设置过滤:

    <project>
      ...
      <build>
        ...
        <resources>
          <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
          </resource>
          ...
        </resources>
        ...
      </build>
      ...
    </project>
    

    【讨论】:

    • 我的 pom.xml 中已经有了这些 Maven 设置,但我想知道为什么 FileUtils 找不到资源。不过,它适用于您的建议,谢谢。
    【解决方案2】:

    @khmarbaise 解决方案对我不起作用,因此我结合了资源过滤(Dmitriy Tarasov 示例)和使用 AssetManager 加载资产(描述为here)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多