将 byte[] 转换为 ArrayList<String>

4

我在stackoverflow上发现了一个问题:将ArrayList<String>转换为byte []

这个问题是关于如何将ArrayList<String>转换为byte[]

那么,是否有可能将byte[]转换为ArrayList<String>呢?


1
如果你无法将其转换回去,为什么要将某物转换为字节数组?我不知道为什么你接受了那个答案。因为它无法产生与用于创建字节数组的字符串列表相等的结果。 - Dunes
可能是什么是字符编码,为什么我要关心它的重复问题。 - Raedwald
4个回答

8

看起来没有人读原始问题 :)

如果你使用第一个答案中的方法将每个字符串单独序列化,那么做完全相反的操作将得到所需的结果:

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

6

这样的内容应该足够了,如果有编译错误,请原谅,我只是在这里匆忙地写了出来。

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

最好作为一个新问题来询问,Ali,提供更多关于你想要实现的具体示例。 - Brian
@Ali:你是指将String[]转换为ArrayList<String>吗?如果是的话,你可以使用Arrays.asList。 - Sid Malani
@SidMalani:不,只是将字符串转换为ArrayList<String>。 - iSun
1
@Ali Arrays.asList(string.split("")); 我猜你想要按每个字符拆分。我认为这会在第一个元素中引入一个空格,但你可以轻松地将其删除。 - Sid Malani

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构造函数——这足以让您开始了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接