将byte []转换为ArrayList <string> </string>

时间:2011-12-15 16:57:26

标签: java

我在SO上发现了一个问题:Convert ArrayList<String> to byte []

关于将ArrayList<String>转换为byte[]

现在可以将byte[]转换为ArrayList<String>吗?

4 个答案:

答案 0 :(得分: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();
        }
    }
}

答案 1 :(得分:5)

这样的事情应该足够了,原谅任何编译错字我只是在这里喋喋不休:

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

答案 2 :(得分:3)

是的可能,从字节数组中取出每个项目并转换为字符串,然后添加到arraylist

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

答案 3 :(得分:1)

它很大程度上取决于你对这种方法的期望。最简单的方法是new String(bytes, "US-ASCII") - 然后将其拆分为您想要的详细信息。

显然存在一些问题:

  1. 我们怎样才能确定它是"US-ASCII"而不是"UTF8"或者说"Cp1251"
  2. 什么是字符串分隔符?
  3. 如果我们希望其中一个字符串包含分隔符,该怎么办?
  4. 依此类推。但最简单的方法是调用String构造函数 - 这足以让你开始。

相关问题