1

我想从配置文件初始化应用程序。在android中创建只读文件的最佳方法是什么?我知道 Asset Folder 是只读的。这是我的配置管理器

配置管理器

public class ConfigManager {
    private static final String CONFIG_FILE         = "config";
    private static final String KEY_VALUE_SEPERATOR = "=";

    public static String loadConfig(Context context, String key) {
        List<String> lines = FileManager.readFromFile(context, CONFIG_FILE);
        Map<String, String> allConfig = parseLines(lines);
        return allConfig.get(key);
    }
    //For Writable Config File
    public static boolean saveConfig(Context context, Config config) {
        List<String> lines = new ArrayList<String>();
        lines.add(config.key + KEY_VALUE_SEPERATOR + config.value);
        return FileManager.writeToFile(context, CONFIG_FILE, lines);
    }

    private static Map<String, String> parseLines(List<String> lines) {
        Map<String, String> out = new HashMap<String, String>();
        for(String line : lines) {
            Config config = parseKeyAndValueFromLine(line);
            out.put(config.key, config.value);
        }
        return out;
    }

    private static Config parseKeyAndValueFromLine(String line) {
        Config out = new Config();
        int seperatorIdx = line.indexOf(KEY_VALUE_SEPERATOR);
        if(-1 == seperatorIdx) return out;
        String key = line.substring(0, seperatorIdx);
        out.key = key.trim();
        String value = line.substring(seperatorIdx + 1);
        out.value = value.trim();
        return out;
    }
}
4

1 回答 1

3

在 assets 目录中创建一个属性文件;例如,app.properties。然后在代码中,您可以这样访问:

try {
    InputStream inputStream = assetManager.open("app.properties");
    Properties properties = new Properties();
    properties.load(inputStream);
    System.out.println("The properties are now loaded");
    System.out.println("properties: " + properties);
} catch (IOException e) {
    e.printStackTrace();
}
于 2013-10-10T19:23:57.680 回答