在我的(非 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}而不是版本 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);