简体   繁体   English

如何从内部存储中读取对象?

[英]How to read an object from internal storage?

I've saved objects into myfile.txt. 我已将对象保存到myfile.txt中。 I'm confused about how to read an object from internal storage. 我对如何从内部存储中读取对象感到困惑。 Can anybody help me? 有谁能够帮助我? I'd like to use part of that object in an app similar to the memo app. 我想在类似于备忘录应用程序的应用程序中使用该对象的一部分。

How did you save those objects? 你是如何保存这些物品的? Some sort of serialization?Did you implement java.io.Serializable ? 某种序列化?你实现了java.io.Serializable吗?

To read a text file from the internal storage is quite easy: 从内部存储中读取文本文件非常简单:

    FileInputStream fis;
    try {
        fis = openFileInput("myfile.txt");
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader br = new BufferedReader(isr);
        String data = br.readLine();
        Log.i("Reading file" , data);
    } catch (FileNotFoundException e) {
        Log.w("Reading file" , "Unable to open file");
    } catch (IOException e) {
        Log.w("Reading file" , "Error reading file");
    }

So, basically, the only thing you need to add now is a way to parse the txt file you saved, which should not be so difficult if you know the format... 所以,基本上,你现在唯一需要添加的是一种解析你保存的txt文件的方法,如果你知道格式的话,这应该不会那么困难......

toString() shouldn't be used to write objects. toString()不应该用于编写对象。 As long as you didn't override the toString() in your own class, it will only prompt the object id. 只要你没有覆盖自己类中的toString() ,它就只会提示对象id。 You can't recreate the object by only using this id. 您不能仅使用此ID重新创建对象。

To save an object in a file, you should read about serialization. 要将对象保存在文件中,您应该阅读有关序列化的内容。

Another possibility which works for simple objects is to override the toString() to print all stored data in a specific way (like csv, xml) and to create a parser, that recreates an object with the given values. 另一种适用于简单对象的可能性是覆盖toString()以特定方式(如csv,xml)打印所有存储的数据,并创建一个解析器,重新创建具有给定值的对象。 That will only work on simple objects with simple data types.. 这只适用于具有简单数据类型的简单对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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