1、Socket serverSocket;
2、ObjectOutputStream oWriter;
3、ObjectInputStream oReader;
4、NetInfo netinfo;      //这个是自己制造的类5、oWriter = new ObjectOutputStream(serverSocket.getOutputStream());
6、oWriter.writeObject(netinfo);
7、oWriter.flush();8、oReader = new ObjectInputStream(serverSocket.getInputStream());
9、netinfo=(NetInfo)oReader.readObject();为什么在执行6时,出现NotSerializableException异常?如何使用流直接处理对象?请教各位,最好有事例,谢谢了!

解决方案 »

  1.   

    NetInfo implements Serializable?
      

  2.   

    ObjectOutputStream用于序列化.
    序列化需要implements Serializable.其实楼主的意图也就是序列化与反序列化嘛,重载readObject(java.io.ObjectInputStream in)/writeObject(java.io.ObjectOutputStream out)
      

  3.   

    import ...
    /**
     * @author ly
     */
    public class NetInfo implements Serializable
    {
    int iNetInfo=0;
    int iAbc=0;
    String sNetInfo="abc";
    NetInfo nNetInfo;
    private void readObject(ObjectInputStream ois) throws Exception {
    iNetInfo=ois.readInt();
    sNetInfo=(String)ois.readObject();
    nNetInfo=(NetInfo)ois.readObject();
    }

    private void writeObject(ObjectOutputStream oos) throws Exception
    {
    oos.writeInt(iNetInfo);
    oos.writeObject(sNetInfo);
    oos.writeObject(nNetInfo);
    }
    public String toString()
    {
    String abc=super.toString()+":"+iNetInfo+"/"+iAbc+"/"+sNetInfo;
    if(nNetInfo!=null)abc+="/"+nNetInfo;
    else{abc+="/[null]";}
    return abc;
    }
    public static void main(String[] args) {
    NetInfo netInfo=new NetInfo();
    netInfo.iNetInfo=1;
    netInfo.iAbc=5;
    netInfo.sNetInfo="abcdef";
    NetInfo netInfo2=new NetInfo();
    netInfo2.iNetInfo=4;
    netInfo.nNetInfo=netInfo2;
    FileOutputStream fos=null;
    FileInputStream fis=null;
    ObjectOutputStream oos=null;
    ObjectInputStream ois=null;
    try {
    fos=new FileOutputStream(new File("C:\\a.txt"));
    oos=new ObjectOutputStream(fos);
    oos.writeObject(netInfo);
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }finally{
    if(fos!=null)try{fos.close();}catch(Exception e){}
    if(oos!=null)try{fos.close();}catch(Exception e){}
    }
    try {
    fis=new FileInputStream(new File("C:\\a.txt"));
    ois=new ObjectInputStream(fis);
    NetInfo netInfo3=(NetInfo) ois.readObject();
    System.out.println(netInfo3);
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }finally{
    if(fis!=null)try{fis.close();}catch(Exception e){}
    if(ois!=null)try{fis.close();}catch(Exception e){}
    }

    }}
      

  4.   

    上面的例子可以看出除了iAbc在序列化时没有被序列,所以结果中取不到它的值之外,其余的值都可以取到.
    执行结果如下:
    NetInfo@1690726:1/0/abcdef/NetInfo@5483cd:4/0/abc/[null]
    另外:在C:\\a.txt中:
     sr NetInfo檉? HM? I iAbcI iNetInfoL nNetInfot  LNetInfo;L sNetInfot Ljava/lang/String;xpw   t abcdefsq ~  w   t abcpxx