簡體   English   中英

將byte []轉換為ArrayList <String>

[英]Convert byte[] to ArrayList<String>

我在SO上找到了一個問題: 將ArrayList <String>轉換為byte []

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

現在可以將byte[]轉換為ArrayList<String>嗎?

看起來沒有人讀原來的問題:)

如果您使用第一個答案中的方法分別序列化每個字符串,則完全相反的操作將產生所需的結果:

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

像這樣的東西應該足夠了,原諒任何編譯錯字我只是在這里喋喋不休:

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

是的可能,從字節數組中取出每個項目並轉換為字符串,然后添加到arraylist

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

它很大程度上取決於你對這種方法的期望。 最簡單的方法是使用new String(bytes, "US-ASCII") - 然后將其拆分為您想要的詳細信息。

顯然有一些問題:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM