Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an ArrayList to file and retrieve it?

Tags:

android

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

like image 211
lamp ard Avatar asked Aug 28 '12 11:08

lamp ard


People also ask

How do I retrieve from an ArrayList?

An element can be retrieved from the ArrayList in Java by using the java. util. ArrayList. get() method.

How do I print an ArrayList from an array?

These are the top three ways to print an ArrayList in Java: Using a for loop. Using a println command. Using the toString() implementation.


2 Answers

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.

like image 128
flawyte Avatar answered Nov 16 '22 02:11

flawyte


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

like image 31
Gagan Avatar answered Nov 16 '22 03:11

Gagan