2016-12-30 35 views
2

我試圖將用戶設置保存到一個文件,從那裏我可以讀取以後。但我無法讓它正常工作。我已經嘗試閱讀這個,但我仍然有問題。如何在Android中將HashMap保存到文件中?

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

我已經讀取和寫入應用程序的權利。

我沒有得到任何東西。我檢查了hashmap,它按預期工作。我也嘗試了很多不同的方法,並且我設法做的唯一工作就是將字符串保存爲.txt文件。

+0

「我沒有得到任何東西。」這是你的問題?如果你想我們理解,請更具體。 – davidxxx

+0

FileOutputStream.flush(),然後關閉它! – Fang

+0

@Jason這些東西在關閉時會自動刷新。這不是問題。 – GhostCat

回答

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

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

問題只是與文件路徑有關。

0

你的問題很簡單:在寫入數據時你使用了兩個不同的文件名。閱讀它。

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

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

而且,最有可能的,你閱讀代碼做你拋出IOException,告訴你關於試圖打開一個不存在的文件的東西。

因此,真正的外賣/答案在這裏:非常仔細地閱讀這些異常消息。通常,他們確切地告訴你問題是什麼!

+0

是的,我得到一個消息,該文件不存在。 「W/System.err:java.io.FileNotFoundException:...」 – JesperN

+0

請看,正如我告訴你的那樣:閱讀郵件。當你不能讀取文件時...檢查你正在使用的名字! – GhostCat

0

更改這些行:

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

感謝您的努力。我嘗試了你的方法,它像一個魅力。更好地使用許多安全功能。 – JesperN

0

如果僅僅是要存儲,那麼你應該使用SharedPreferences其Android提供開箱即用的原語。

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(); 
} 
相關問題