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>
?
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();
}
}
}
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