Serialization is a mechanism in which an object can be represented as a sequence of bytes that includes object data, as well as information about the type of object and the types of data stored in the object.
ArrayList already implements Serializable, so in your example you can write something like this:
ArrayList<String> al=new ArrayList<String>(); al.add("Jean"); al.add("Pierre"); al.add("John"); try{ FileOutputStream fos= new FileOutputStream("myfile.txt"); ObjectOutputStream oos= new ObjectOutputStream(fos); oos.writeObject(al); oos.close(); fos.close(); }catch(IOException ioe){ ioe.printStackTrace(); }
Here we save the list al in the file myfile.txt.
To read the file and return an ArrayList, you must use an ObjectInputStream:
FileInputStream fis = new FileInputStream("myfile.txt"); ObjectInputStream ois = new ObjectInputStream(fis); ArrayList<String> list = (ArrayList<String>) ois.readObject(); ois.close();
source share