gpt4 book ai didi

java - getResourceAsStream 返回 null,尽管被调用的文件与类 getResourceAsStream 位于同一目录中

转载 作者:太空狗 更新时间:2023-10-29 15:53:11 26 4
gpt4 key购买 nike

我导入了一个由 Amazon 编码的 Android 示例,涉及我从这里获得的 AWS 的 DynamoDB,并且大概是为 Eclipse 编写的: https://github.com/awslabs/aws-sdk-android-samples/tree/master/DynamoDBMapper_UserPreference

由于 Android Studio (0.8.1) 使用 gradle 而不是 ant,因此在导入时自然会根据目录结构自动移动,因此(部分)看起来像这样:

enter image description here

PropertyLoader 从 AwsCredentials.properties 获取连接到数据库 DynamoDB 所需的 TVM 凭据信息。相关方法:

public class PropertyLoader {

private boolean hasCredentials = false;
private String tokenVendingMachineURL = null;
private boolean useSSL = false;
private String testTableName = null;

private static PropertyLoader instance = null;

public static PropertyLoader getInstance() {
if ( instance == null ) {
instance = new PropertyLoader();
}

return instance;
}

public PropertyLoader() {
try {
Properties properties = new Properties();
properties.load( this.getClass().getResourceAsStream( "AwsCredentials.properties" ) );

this.tokenVendingMachineURL = properties.getProperty( "tokenVendingMachineURL" );
this.useSSL = Boolean.parseBoolean( properties.getProperty( "useSSL" ) );
this.testTableName = properties.getProperty( "testTableName" );

if ( this.tokenVendingMachineURL == null || this.tokenVendingMachineURL.equals( "" ) || this.tokenVendingMachineURL.equals( "CHANGEME" ) || this.testTableName.equals( "" ) ) {
this.tokenVendingMachineURL = null;
this.useSSL = false;
this.hasCredentials = false;
this.testTableName = null;
}
else {
this.hasCredentials = true;
}
}
catch ( Exception exception ) {
Log.e( "PropertyLoader", "Unable to read property file." );
}
}

但是 getResourceAsStream 行 properties.load( this.getClass().getResourceAsStream( "AwsCredentials.properties") ); 返回 null。正如您在我的屏幕截图中看到的那样,AwsCredentials.properties 与 PropertyLoader 位于同一目录中并且匹配大小写,根据我对该方法的阅读,这是所有应该需要的: http://mindprod.com/jgloss/getresourceasstream.html

getResourceAsStream() is always returning null

我尝试了其他方法,例如前缀“\”(即 properties.load( this.getClass().getResourceAsStream( "\AwsCredentials.properties") ); 并复制凭据文件和放置在 src 文件夹中(您无法在此屏幕截图中看到它,因为资源管理器按文件类型(?)排序并首先放置“main”,但它在那里)按照此:

getResourceAsStream returning null

但是,这也没有解决问题。在尝试了这些选项并进行了研究之后,我对它返回 null 的原因感到困惑。我该如何解决这个问题?

最佳答案

在/src/main/下创建了一个名为 resources 的目录,并将 AwsCredentials.properties 放在那里并使用

properties.load( PropertyLoader.class.getClassLoader().getResourceAsStream( "AwsCredentials.properties" ) );

代替

properties.load( this.getClass().getResourceAsStream("AwsCredentials.properties" ) );

虽然没有我想要的那么优雅,但它确实有效。

关于java - getResourceAsStream 返回 null,尽管被调用的文件与类 getResourceAsStream 位于同一目录中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24661229/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com