繁体   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