2011-12-15 93 views
4

我發現了一個問題,在這裏這樣:Convert ArrayList<String> to byte []轉換字節[]到ArrayList的<String>

它是關於轉換ArrayList<String>byte[]

現在有可能將byte[]轉換成ArrayList<String>

+1

如果你不能將它轉換回來,你爲什麼要把某些東西變成一個字節數組?我不知道你爲什麼接受你所做的答案。因爲它不會產生與用於創建字節數組的字符串列表相同的字符串列表。 – Dunes 2011-12-15 17:19:56

+0

[什麼是字符編碼,爲什麼我應該打擾它]可能的重複(http://stackoverflow.com/questions/10611455/what-is-character-encoding-and-why-should-i-bother-with-它) – Raedwald 2015-04-10 12:09:26

回答

5

像這樣的東西應該足夠了,原諒任何編譯錯別字我剛慌亂它在這裏:

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

Np。最好問一個作爲一個新的問題阿里,更多的例子,你到底想要達到什麼 – Brian 2011-12-15 17:28:08

3

耶的可能,從字節數組採取的每一項,並轉換爲字符串,然後添加到ArrayList中

String str = new String(byte[i]); 
arraylist.add(str); 
1

它很大程度上取決於您對這種方法期望的語義。最簡單的方法是,new String(bytes, "US-ASCII") - 然後將其分解成您想要的細節。

顯然有一些問題:

  1. 我們怎樣才能確保它的"US-ASCII"而不是"UTF8",或者說,"Cp1251"
  2. 什麼是字符串分隔符?
  3. 如果我們想要其中一個字符串包含一個分隔符怎麼辦?

等等等等。但最簡單的方法確實是調用String構造函數 - 它足以讓你開始。

7

貌似沒人讀了原來的問題:)

如果從第一個答案用什麼方法來單獨序列的每個字符串,這樣做完全相反會得到所需要的結果:

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

如果你的byte []包含ArrayList本身,你可以這樣做:

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(); 
     } 
    } 
} 
相關問題