How to read an object from internal storage?
I开发者_StackOverflow've saved objects into 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
?
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...
toString()
shouldn't be used to write objects. As long as you didn't override the toString()
in your own class, it will only prompt the object id. You can't recreate the object by only using this 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. That will only work on simple objects with simple data types..
精彩评论