我在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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你的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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这样的事情应该足够了,原谅任何编译错字我刚刚在这里喋喋不休:
for(int i = 0; i < allbytes.length; i++)
{
String str = new String(allbytes[i]);
myarraylist.add(str);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8690 次 |
| 最近记录: |