Save an arraylist to cache file and retrieve it
<p>I want to create two methods. The one should store and arraylist to the cache and the other should retrieve the arraylist from the cache. The code that I've tried is the following:</p>

<pre><code>public class ByteConverter&lt;T&gt; {

public byte[] write_to_byte_array(ArrayList&lt;T&gt; list,File file){

    // write to byte array
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(file);
    } catch (FileNotFoundException e1) {
        Log.d("file not found", "file not found", e1);
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(baos);
    for (T element : list) {
        try {
            out.writeUTF((String) element);
        } catch (IOException e) {
            Log.d("Error converting List to byte array", "Error converting List to byte array", e);
        }
    }

    byte[] bytes = baos.toByteArray();

    int len1 = 0;
    while (len1 &lt; bytes.length) {
        try {
            fos.write(bytes, 0, len1);
            len1++;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return bytes;

}

public String read_to_byte_array(byte[] bytes) throws IOException{

    // read from byte array
    String element = null;
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    DataInputStream in = new DataInputStream(bais);
    while (in.available() &gt; 0) {
        element = in.readUTF();
    }

    return element; 
}

  }
</code></pre>

<p>However the aforementioned methods doesn't write anything to the file. I don't know why. Can anyone help me? Also I'm taking a ClassCastException at this line: </p>

<pre><code>       out.writeUTF((String) element);
</code></pre>
