如何将hashmap保存到Android中的文件



我正在尝试将用户设置保存到文件,以后可以阅读。但是我不能使它正常工作。我已经尝试阅读此内容,但我仍然有问题。

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文件中。

 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();
        }
    }
}

您的问题非常简单:编写数据resp时,您正在使用两个不同的文件名。读它。

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

vs。

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

,很可能是您的读取代码确实向您投掷IOException,并告诉您一些有关尝试打开不存在的文件的信息。

因此,在这里真正的外卖/答案:非常仔细地阅读这些异常消息。通常,他们确切地告诉您问题是什么!

更改以下行:

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();
}

如果仅是要存储的原始词,则应使用Android开箱即用的共享Preferences。

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();
}

最新更新