private int type;private String from, to, content;/**
 * 解包
 */
public QQPacket(byte[] bs) {
ByteArrayInputStream bais = new ByteArrayInputStream(bs);
DataInputStream dis = new DataInputStream(bais); try {
this.type = dis.readInt();
this.from = dis.readUTF();
this.to = dis.readUTF();
this.content = dis.readUTF();
} catch (IOException e) { e.printStackTrace();
} } /**
 * 将字段转换成字节数组,即打包
 * 
 * @return
 */
public byte[] toByteArray() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos); try {
dos.writeInt(type);
dos.writeUTF(from);
dos.writeUTF(to);
dos.writeUTF(content); } catch (IOException e) {
e.printStackTrace();
}
return baos.toByteArray();
}
问题:
以上是传输的网络包,我想把其中一个String类型的数据(比如String from, to, content)改成Map类型.请问以上如何修改?

解决方案 »

  1.   

    对象序列化,ObjectOutputStream,ObjectInputStream
      

  2.   

    我想把其中一个String类型的数据(比如String from, to, content)改成Map类型.请问以上如何修改
    Map是java的容器
    Map提供key到value的映射
    Map接口提供3种集合的视图,Map的内容可以被当作一组key集合,一组value集合,或者一组key-value映射
    直接用新建map ,直接用put就可以把对象放进去了
      

  3.   

    答:可以修改如下:
    public QQPacket(byte[] bs) { 
    ByteArrayInputStream bais = new ByteArrayInputStream(bs); 
    ObjectInputStream ois = new ObjectInputStream(bais); try { 
    this.type = ois.readInt(); 
    this.from = (Map)ois.readObject(); 
    this.to = (Map)ois.readObject(); 
    this.content = (Map)ois.readObject(); 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } } public byte[] toByteArray() { 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    ObjectOutputStream oos = new ObjectOutputStream(baos); try { 
    oos.writeInt(type); 
    oos.writeObject(from); 
    oos.writeObject(to); 
    oos.writeObject(content); } catch (IOException e) { 
    e.printStackTrace(); 

    return baos.toByteArray(); 
    } 以上仅供你参考