now im trying to use this
FileOutputStream fos = getContext().openFileOutput("CalEvents", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(returnlist);
oos.close();
in order to save "returnlist" which is an ArrayList to the file "CalEvents" now my question is , is that the right way to do it? and how do i retrieve the list back?
thanks in advance
An element can be retrieved from the ArrayList in Java by using the java. util. ArrayList. get() method.
These are the top three ways to print an ArrayList in Java: Using a for loop. Using a println command. Using the toString() implementation.
Is this what you want to do ?
FileInputStream fis;
try {
fis = openFileInput("CalEvents");
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Object> returnlist = (ArrayList<Object>) ois.readObject();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
EDIT: Can be simplified:
FileInputStream fis;
try {
fis = openFileInput("CalEvents");
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Object> returnlist = (ArrayList<Object>) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
Assuming that you are in a class which extends Context
(like Activity
). If not, then you will have to call the openFileInput()
method on an object which extends Context
.
Use this method to write your Arraylist in a file
public static void write(Context context, Object nameOfClass) {
File directory = new File(context.getFilesDir().getAbsolutePath()
+ File.separator + "serlization");
if (!directory.exists()) {
directory.mkdirs();
}
String filename = "MessgeScreenList.srl";
ObjectOutput out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(directory
+ File.separator + filename));
out.writeObject(nameOfClass);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Complete example here, with Read method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With