我在stackoverflow上发现了一个问题:将ArrayList<String>转换为byte []
这个问题是关于如何将ArrayList<String>
转换为byte[]
。
那么,是否有可能将byte[]
转换为ArrayList<String>
呢?
我在stackoverflow上发现了一个问题:将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();
}
}
}
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")
,然后将其拆分为所需的详细信息。
显然存在一些问题:
"US-ASCII"
而不是"UTF8"
或者"Cp1251"
?等等等等。但最简单的方法确实是调用String
构造函数——这足以让您开始了。