0

我正在尝试创建一个利用 Java Properties 类的 Eclipse Android 项目。对于该项目,我的 src 目录中有一个配置文本文件,其中包含键值对。我还有一个配置类,它包含一个属性对象,用于最初读取配置文件以及在整个执行过程中访问各种属性。但是,我在访问某些属性时遇到了一些错误。我想查看我正在生成的属性文件,以便我可以更轻松地进行调试。我该怎么做呢?

public static Properties prop;

static {

    AssetManager assetManager = getApplicationContext().getAssets();
    InputStream instream = assetManager.open("config");
    readConfig(instream);

}

private static void readConfig(Inputstream instream) {

    try {
        String line = "";
        BufferedReader read = new BufferedReader(instream);

        while ((line = read.readLine()) != null) {
            String[] split_line = line.split("=", 2);
            prop.setProperty(split_line[0], split_line[1]);
        }

        prop.store(new FileOutputStream("config.properties"), "Default and local config files");
        read.close();
    }
    catch (Exception e) {
        Log.d("cool", "Failed to create properly initialize config class");
    }
}

public static String getProperty (String propertyKey) {

    try {
        return prop.getProperty(propertyKey);
    }
    catch (Exception e) {
        Log.d("cool", "Failed to access property");
        return null;
    }
}
4

1 回答 1

0

我不太明白您要做什么,但是如果您想从文本文件中读取一些键/值对,那么您不应该将此文本文件放在您的 src 目录中,这就是 assets 目录的用途。您可以通过像这个 file:///android_asset/... 这样的 Uri 访问资产目录中的所有文件,或者最好使用以下代码:

AssetManager assetManager = getAssets();
InputStream instream = assetManager.open("file.txt");

编辑:尝试像这样实现您的 Config 类:

public class Config
{
    private static Config instance;
    public static Config getInstance(Context context)
    {
         if(instance == null)
         {
             instance = new Config(context);
         }
         return instance;
    }

    protected Config(Context context)
    {
       AssetManager manager = context.getAssets();
       ...
    }
}

然后,您可以在代码中使用 Config 类,如下所示:

Config config = Config.getInstance(getApplicationContext());
config.getProperty(...);
于 2013-07-15T18:10:06.110 回答