繁体   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