简体   繁体   English

Android 工作室商店 map<string, integer> 在带有属性的 file.properties 中</string,>

[英]Android studio store map<String, Integer> in file.properties with properties

I'm trying to save file.properties.我正在尝试保存 file.properties。 I can save a <String, String> map.我可以保存一个 <String, String> map。

But when I try to save a <String, Integer> map I get an error.但是当我尝试保存 <String, Integer> map 时出现错误。

Is there a way to save a <String, Integer> map?有没有办法保存 <String, Integer> map?

The code that does not work:不起作用的代码:

    Map<String, Integer> int_map = new HashMap<String, Integer>();
    int_map.put("Red", 4);
    int_map.put("Orange-red", 3);
    int_map.put("Orange", 2);
    int_map.put("Green", 1);
    int_map.put("Blue", 0);

    Properties properties = new Properties(); // Crate properties object to store the data

    for (Map.Entry<String, Integer> entry : int_map.entrySet()) {
        properties.put(entry.getKey(), entry.getValue());
    }

    try {
        properties.store(new FileOutputStream(this.getFilesDir() + "data.properties"), null);
    } catch (IOException e) {
        e.printStackTrace();
    }

The code that works:有效的代码:

        Map<String, String> map = new HashMap<String, String>();

        map.put("hello", "world");
        
        Properties properties = new Properties(); // Crate properties object to store the data

        for (Map.Entry<String, String> entry : map.entrySet()) {
            properties.put(entry.getKey(), entry.getValue());
        }

        try {
            properties.store(new FileOutputStream(this.getFilesDir() + "data.properties"), null);
        } catch (IOException e) {
            e.printStackTrace();
        }

The error that I get when I try to run it:我尝试运行它时遇到的错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.trialanderror, PID: 24139
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.trialanderror/com.example.trialanderror.MainActivity}: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3555)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3707)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2220)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:237)
        at android.app.ActivityThread.main(ActivityThread.java:8016)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1087)
     Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
        at java.util.Properties.store0(Properties.java:836)
        at java.util.Properties.store(Properties.java:820)
        at com.example.trialanderror.MainActivity.onCreate(MainActivity.java:36)
        at android.app.Activity.performCreate(Activity.java:7957)
        at android.app.Activity.performCreate(Activity.java:7946)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3530)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3707) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2220) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:237) 
        at android.app.ActivityThread.main(ActivityThread.java:8016) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1087) 

It is by design.这是设计使然。

From documentation we can read:文档中我们可以阅读:

Because Properties inherits from Hashtable , the put and putAll methods can be applied to a Properties object.因为Properties继承自Hashtable ,所以putputAll方法可以应用于 Properties object。 Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings .强烈建议不要使用它们,因为它们允许调用者插入键或值不是字符串的条目 The setProperty method should be used instead.应该改用setProperty方法。 If the store or save method is called on a "compromised" Properties object that contains a non-String key or value, the call will fail.如果在包含非字符串键或值的“受损”属性 object 上调用storesave方法,则调用将失败。

(emphasis mine). (强调我的)。

In other words you need to only store String objects for keys and values.换句话说,您只需要为键和值存储字符串对象。 If you have Integer, convert it to String and then write it to Properties.如果您有 Integer,请将其转换为字符串,然后将其写入属性。 In your case instead of在你的情况下,而不是

properties.put(entry.getKey(), entry.getValue());

you may want to use something like你可能想使用类似的东西

properties.setProperty(entry.getKey(), entry.getValue().toString());
//        |                                            ^-- convert Integer to String
//        |
//        ^--use `setProperty(String key, String value)` method instead of
//           `put(K key, V value)` to let compiler enforce String as key and value

OR if map can contain null value and instead of getting NPE you want to store it as String "null" use Objects.toString(entry.getValue()) instead of entry.getValue().toString() .或者,如果 map 可以包含null值,而不是获取 NPE,您希望将其存储为字符串"null"使用Objects.toString(entry.getValue())而不是entry.getValue().toString()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM