Convert ArrayList to byte array
arraylist, java, mysql
Solution
I have added sample coding for convert ArrayList to byte[].
One reasonable way would be to use UTF-8 encoding like DataOutputStream does for each string in the list. For a string it writes 2 bytes for the length of the UTF-8 encoding followed by the UTF-8 bytes.
This would be portable if you're not using Java on the other end. Here's an example of encoding and decoding an ArrayList:
// example input list
List<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
list.add("baz");
// write to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
for (String element : list) {
out.writeUTF(element);
}
byte[] bytes = baos.toByteArray();
// read from byte array
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
DataInputStream in = new DataInputStream(bais);
while (in.available() > 0) {
String element = in.readUTF();
System.out.println(element);
}
Problem
I have a code where I am converting array list to byte array and then saving that byte array as a BLOB in MySQL database. Below is code:- ``` Object temp = attributes.get(columnName); if (temp instanceof List && temp != null) { List extraAttributes = (ArrayList) temp; resultStmt.setBytes(currentIndex, createByteArray(extraAttributes)); ``` The method `createByteArray` is defined as below: ``` private byte [] createByteArray( Object obj) { byte [] bArray = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream objOstream = new ObjectOutputStream(baos); objOstream.writeObject(obj); bArray = baos.toByteArray(); } catch (Exception e) { TraceDbLog.writeError("Problem in createByteArray", e); } return bArray; } ``` Well the above code was written earlier for writing HashMap to BLOB i am using same for converting ArrayList if HashMap to BLOB. The problem which is occurring in read code when i am reading the blob. ``` private Object readBytes (ResultSet rs, String columnName) throws SQLException { ObjectInputStream ois = null; byte [] newArray; Object obj = null; try { newArray = rs.getBytes(columnName); ois = new ObjectInputStream (new ByteArrayInputStream(newArray)); obj = ois.readObject (); } ``` In the read part the object is not coming as arrayList of hasMap and in debug perspective in eclipse eclipse is also not able to inspect the object which is coming. I have also tried typecasting the object to List but still no success in getting the right response. Please tell me whether there is any flaw in reading/writing the above BLOB.