簡體   English   中英

如何在Java / Android中以最有效的方式讀取txt復雜哈希圖

[英]How to read a txt complex hashmap in the most efficient way in Java/Android

這是我的將哈希映射寫入txt的代碼。

//In a previous method:
private Context contexta = MainActivity.this;
writeToFile(my_hashmap.toString(), contexta);

然后是方法writeToFile

private void writeToFile(String data,Context context) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }

我的哈希映射my_hashmap的構建方式類似於hashmap(String, hashmap2(String, hashmap3(String, Integer)))

所以我的文本文件包含:

A_string1={{B_string1={C_string1=0, C_string2=0, C_string3=0}, B_string2={...}...}, A_string2={...}, ...

從文件中再次讀取的最有效方法是什么?

重要提示: 我希望它在.txt文件中可讀! 據我所知,序列化對我來說將不起作用,因為它會創建不可讀的數據。 我不想更改writeToFile方法,這只是編碼readFromFile的一種聰明方法。

您可以使用ObjectOutputStream(new FileOutputStream(file)); 寫文件


new ObjectInputStream(new FileInputStream(file))讀取文件

寫入檔案

  File file = new File("filePath");
  FileOutputStream f = new FileOutputStream(file);
  ObjectOutputStream s = new ObjectOutputStream(f);
  s.writeObject(fileObj);
  s.close();

從文件讀取

    File file = new File("filePath");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
HashMap<String, Object> fileObj2 = (HashMap<String, Object>) s.readObject();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM