Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert byte[] to ArrayList<String>

Tags:

java

I found a question here on SO: Convert ArrayList<String> to byte []

It is about converting ArrayList<String> to byte[].

Now is it possible to convert byte[] to ArrayList<String> ?

like image 698
iSun Avatar asked Dec 03 '22 05:12

iSun


1 Answers

Looks like nobody read the original question :)

If you used the method from the first answer to serialize each string separately, doing exactly the opposite will yield the required result:

    ByteArrayInputStream bais = new ByteArrayInputStream(byte[] yourData);
    ObjectInputStream ois = new ObjectInputStream(bais);
    ArrayList<String> al = new ArrayList<String>();
    try {
        Object obj = null;

        while ((obj = ois.readObject()) != null) {
            al.add((String) obj);
        }
    } catch (EOFException ex) { //This exception will be caught when EOF is reached
        System.out.println("End of file reached.");
    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        //Close the ObjectInputStream
        try {
            if (ois != null) {
                ois.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

If your byte[] contains the ArrayList itself, you can do:

    ByteArrayInputStream bais = new ByteArrayInputStream(byte[] yourData);
    ObjectInputStream ois = new ObjectInputStream(bais);
    try {
        ArrayList<String> arrayList = ( ArrayList<String>) ois.readObject();
        ois.close();
    } catch (EOFException ex) { //This exception will be caught when EOF is reached
        System.out.println("End of file reached.");
    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        //Close the ObjectInputStream
        try {
            if (ois!= null) {
                ois.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
like image 101
soulcheck Avatar answered Dec 21 '22 10:12

soulcheck