Convert Byte [] to ArrayList <String>
I found here a question about SO: Convert ArrayList <String> to Byte []
It's about converting an ArrayList<String> to byte[] .
Can I convert byte[] to ArrayList<String> ?
No one seems to have read the original question :)
If you used the method from the first answer to serialize each line separately, then performing the opposite result will give the desired 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(); } } } it depends a lot on the semantics you expect from such a method. The easiest way is new String(bytes, "US-ASCII") , and then break it down into the details you need.
There are obviously some problems:
- How can we make sure of this is
"US-ASCII"and not"UTF8"or, say,"Cp1251"? - What is a line separator?
- What if we want one of the lines to contain a separator?
And so on and so forth. But the easiest way is to call the constructor String - this will be enough to get you started.