【问题标题】:How to load properties file which is in assets folder?如何加载资产文件夹中的属性文件?
【发布时间】:2016-04-13 09:18:46
【问题描述】:

我正在开发一个 Android 应用程序,我需要在 /app/src/main/assets/app.properties 的 assets 文件夹中读取我的属性。

但是当我使用时:

Properties properties = new Properties();
try {
properties.load(new FileInputStream("app.properties"));
} catch (IOException e) {
...
}

inputStream 似乎是null。我想我必须精确filepath 或类似的东西才能访问我的属性文件。

我需要在这个类中使用我的属性:/app/src/main/java/mypackage/model/myclass.java

【问题讨论】:

标签: java android


【解决方案1】:

您可以像这样使用您的 android 上下文加载属性文件:

context.getAssets().open("app.properties");

例如在片段中:

try{
    Properties properties = new Properties();
    properties.load(this.getActivity().getAssets().open("app.properties"));
}catch(Exception e){
    e.printStackTrace();
}

当您在一个上下文不可访问的类中似乎需要这个时,您可以创建自己的应用程序类,对上下文进行静态访问,然后在任何地方使用这个上下文。

创建您的应用程序类:

public class MyApp extends Application {
    private static MyApp instance;

    public static MyApp getInstance() {
        return instance;
    }

    public static Context getContext(){
        return instance.getApplicationContext()
    }

    @Override
    public void onCreate() {
        instance = this;
        super.onCreate();
    }
}

将新创建的应用程序添加到清单中:

<application
    android:name="com.example.yourapp.MyApp"
    ...

完成此操作后,您可以在 XMLParser 中加载属性:

try{
    Properties properties = new Properties();
    properties.load(MyApp.getContext().getAssets().open("app.properties"));
}catch(Exception e){
    e.printStackTrace();
}

【讨论】:

  • 我不能使用 getActivity().getAssets().... 因为我在一个不是 Activity 的类中,而且我不能使用上下文。我的类是一个 XMLParser,我的属性文件存储了我可以在我的 XML 文件中找到的所有 XML 节点。
  • 查看我的更新答案以将上下文访问到您的解析器中。
  • 谢谢!!!它有效,我不知道我们可以创建一个“虚拟上下文”,而这正是我所需要的。
  • @Nirekin 为什么不在应用程序类的构造函数中设置instance = this
【解决方案2】:

尝试获取资产并让他们阅读:

AssetFileDescriptor fileDescriptor = assetManager.openFd(fileName);
FileInputStream stream = fileDescriptor.createInputStream();
Properties properties = new Properties();
try {
properties.load(stream);
} catch (IOException e) {
...
}

【讨论】:

    【解决方案3】:

    在 /app/src/test/java/mypackage/XMLParserTest 中的单元测试“XMLParserTest”中,我尝试过:

        InputStream is = null;
        Properties prop = null;
        try {
            prop = new Properties();
            is = new FileInputStream(new File("C:/...fullpath.../app/src/main/assets/app.properties"));
            prop.load(is);
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    

    它可以工作,但是当我把它放在我的 XMLParser 类中时,我的 inputStream "is" 为空。 这就像类无法访问文件.properties。它仅适用于测试......

    【讨论】:

      【解决方案4】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-10
        • 2022-01-21
        • 1970-01-01
        • 2011-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多