简体   繁体   中英

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

Here is my code to write the hashmap to a txt.

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

Then the method 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 my_hashmap is built like hashmap(String, hashmap2(String, hashmap3(String, Integer)))

So my text file contains:

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

What is the most efficient way to read it again from the file?

Important: I want it to be readable in the .txt ! So as far as I understood Serialization, it will not work for me as it creates non-readable data. I don't want to change the writeToFile method, just a smart way to code a readFromFile.

You can use ObjectOutputStream(new FileOutputStream(file)); to write file
and


new ObjectInputStream(new FileInputStream(file)) to read file

Write to file

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

Read from file

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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