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> ?

+4
source share
4 answers

Something like this should be enough to forgive any compilation typos I just said here:

 for(int i = 0; i < allbytes.length; i++) { String str = new String(allbytes[i]); myarraylist.add(str); } 
+5
source

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

yes, it is possible to take each element from an array of bytes and convert to a string, and then add to arraylist

 String str = new String(byte[i]); arraylist.add(str); 
+3
source

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.

+1
source

Source: https://habr.com/ru/post/1386562/


All Articles