【问题标题】:How to saving a HashMap to a file in Android?如何将 HashMap 保存到 Android 中的文件?
【发布时间】:2017-05-14 12:57:58
【问题描述】:

我正在尝试将用户设置保存到一个文件中,以后可以从中读取。但我无法让它正常工作。我已尝试阅读此内容,但仍然遇到问题。

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

public void updateUserSettings(){

        userSettings.clear();

        userSettings.put("item0", item0);
        userSettings.put("item1", item1);
        userSettings.put("item2", item2);
        userSettings.put("item3", item3);
        userSettings.put("item4", item4);
        userSettings.put("item5", item5);
        userSettings.put("item6", item6);
        userSettings.put("item7", item7);


        userSettings.put("i0", Float.toString(i0));
        userSettings.put("i1", Float.toString(i1));
        userSettings.put("i2", Float.toString(i2));
        userSettings.put("i3", Float.toString(i3));
        userSettings.put("i4", Float.toString(i4));
        userSettings.put("i5", Float.toString(i5));
        userSettings.put("i6", Float.toString(i6));
        userSettings.put("i7", Float.toString(i7));

        userSettings.put("huvudMaskin", huvudMaskin);
        userSettings.put("minorMaskin1", minorMaskin1);
        userSettings.put("minorMaskin2", minorMaskin2);

        userSettings.put("maskinTid", Float.toString(maskinTid));
        writeSettings();
    }



public void writeSettings() {
    try
    {
        FileOutputStream fos = context.openFileOutput("test.ser", Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(userSettings);
        oos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


public void readSetttings() {
    try
    {
        FileInputStream fileInputStream = new FileInputStream(context.getFilesDir()+"test.ser");
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        Map myHashMap = (Map)objectInputStream.readObject();
        userSettings = null;
        userSettings = myHashMap;
    }
    catch(ClassNotFoundException | IOException | ClassCastException e) {
        e.printStackTrace();
    }
    executeSettings();
}

我对应用程序拥有读写权限。

我没有从中得到任何东西。我检查了哈希图,它按预期工作。我也尝试了很多不同的方法,唯一能成功的就是将字符串保存到 .txt 文件中。

【问题讨论】:

  • “我没有从中得到任何东西。”你的问题是什么?如果您希望我们理解,请更具体。
  • FileOutputStream.flush(),然后关闭它!
  • @Jason 这些东西在关闭时会自动刷新。这不是问题。

标签: java android dictionary hashmap save


【解决方案1】:
 private String subFolder = "/userdata";
private String file = "test.ser";

public void writeSettings() {
    File cacheDir = null;
    File appDirectory = null;

    if (android.os.Environment.getExternalStorageState().
            equals(android.os.Environment.MEDIA_MOUNTED)) {
        cacheDir = getApplicationContext().getExternalCacheDir();
        appDirectory = new File(cacheDir + subFolder);

    } else {
        cacheDir = getApplicationContext().getCacheDir();
        String BaseFolder = cacheDir.getAbsolutePath();
        appDirectory = new File(BaseFolder + subFolder);

    }

    if (appDirectory != null && !appDirectory.exists()) {
        appDirectory.mkdirs();
    }

    File fileName = new File(appDirectory, file);

    FileOutputStream fos = null;
    ObjectOutputStream out = null;
    try {
        fos = new FileOutputStream(fileName);
        out = new ObjectOutputStream(fos);
        out.writeObject(userSettings);
    } catch (IOException ex) {
        ex.printStackTrace();
    }  catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (fos != null)
                fos.flush();
            fos.close();
            if (out != null)
                out.flush();
            out.close();
        } catch (Exception e) {

        }
    }
}


public void readSetttings() {
    File cacheDir = null;
    File appDirectory = null;
    if (android.os.Environment.getExternalStorageState().
            equals(android.os.Environment.MEDIA_MOUNTED)) {
        cacheDir = getApplicationContext().getExternalCacheDir();
        appDirectory = new File(cacheDir + subFolder);
    } else {
        cacheDir = getApplicationContext().getCacheDir();
        String BaseFolder = cacheDir.getAbsolutePath();
        appDirectory = new File(BaseFolder + subFolder);
    }

    if (appDirectory != null && !appDirectory.exists()) return; // File does not exist

    File fileName = new File(appDirectory, file);

    FileInputStream fis = null;
    ObjectInputStream in = null;
    try {
        fis = new FileInputStream(fileName);
        in = new ObjectInputStream(fis);
        Map<String, String> myHashMap = (Map<String, String> ) in.readObject();
        userSettings = myHashMap;
        System.out.println("count of hash map::"+userSettings.size() + " " + userSettings);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (StreamCorruptedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }finally {

        try {
            if(fis != null) {
                fis.close();
            }
            if(in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

【讨论】:

  • 感谢您付出的努力。我试过你的方法,效果很好。使用许多安全功能感觉更好。
【解决方案2】:

您的问题很简单:分别在写入数据时使用了两个不同的文件名。阅读它。

FileOutputStream fos = context.openFileOutput("test.ser", Context.MODE_PRIVATE);

对比

FileInputStream fileInputStream = new FileInputStream(context.getFilesDir()+"test.ser");

而且,您的阅读代码很可能确实向您抛出了 IOException,告诉您有关尝试打开不存在的文件的信息。

因此,真正的要点/答案在这里:非常仔细地阅读这些异常消息。通常,他们会准确地告诉您问题所在!

【讨论】:

  • 是的,我确实收到一条消息,指出该文件不存在。 "W/System.err: java.io.FileNotFoundException: ..."
  • 看,正如我告诉你的:阅读消息。当您无法读取文件时...检查您使用的名称!
【解决方案3】:

更改这些行:

public void  readSetttings(){
    String path=context.getFilesDir() + File.seprator + "test.ser";
    if(! new File(path).exists() ){

        //throw NullPointerException ;
        //return;
        /*
        *you can choose one of these
        *pay attention : when choose NullPointerException you shold add throws Exceptions on your method
        */
    }
    try{
        FileInputStream fileInputStream =context.openFileInput("test.ser");
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        Map myHashMap = (Map)objectInputStream.readObject();

        userSettings = myHashMap;
   }catch(ClassNotFoundException | IOException | ClassCastException e) {
       e.printStackTrace();
   }
   executeSettings();
}

【讨论】:

    【解决方案4】:

    如果您只想存储原语,那么您应该使用 Android 开箱即用的SharedPreferences

    public static final String PREFS = "usersettings";
    
    @Override
    protected void onCreate(Bundle b){
       .....
    
       // read user settings on start
       SharedPreferences settings = getSharedPreferences(PREFS, 0);
       int someId = settings.getInteger("someId", 0);
       setSomeId(id);
    }
    
    @Override
    protected void onStop(){
    
      .....
    
      SharedPreferences settings = getSharedPreferences(PREFS, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putInteger("someId", mSomeId);
    
      // commit changes on exit
      editor.commit();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-08
      • 2016-06-23
      • 2016-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      • 2011-04-07
      • 1970-01-01
      相关资源
      最近更新 更多