I’ve been trying to do this for a while but I didn’t find any solution.
I’m working on a shopping list app for android and I have an arraylist of items. I want to write it into a file which will be read everytime the app is opened, to save changes of it. I have a method to write the arraylist, which is this one:
File path = getApplicationContext().getFilesDir();
try {
FileOutputStream fos = new FileOutputStream("output");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(items);
oos.close();
} catch(Exception ex) {
ex.printStackTrace();
}
However I tried many things to read the file and none seem to work. What can I do?
2
Answers
Found the solution. I read the arraylist with this:
public void loadContent(){
In java, you can use a try-witch-resource block.This makes sure that you close the file of something goes wrong. I use BufferReader when I want to read from a while.
In this code snippet, I store each line in an arraylist:
Then you iterate through the file:
I recommend watching a youtube video, or reading on the javadoc for the buffer reader.