0

如何在单个响应中将多个对象写入 ObjectOutputStream(对象不是固定的,对象是根据用户的请求动态创建的)。我可以使用 Arraylist 还是 Vector,请给出一些示例程序。

TexxtViews text=new TexxtViews(2, -2, 2, "WELCOME TO CCS");//First Object
ButtonView button=new ButtonView(-2, 2, "OK");//Second Object
ArrayList array=new ArrayList();
array.add(text);
array.add(button);
   OutputStream out = resp.getOutputStream();
   ObjectOutputStream outSt = new ObjectOutputStream(out);
  outSt.writeObject(array);

试过这段代码

4

1 回答 1

1
public class Employee implements java.io.Serializable
{
   public String name;
   public String address;
   public int transient SSN;
   public int number;
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + name
                           + " " + address);
   }
}






    import java.io.*;

public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;
      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("employee.ser");
         ObjectOutputStream out =
                            new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
          fileOut.close();
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
}

并反序列化回来

 import java.io.*;
   public class DeserializeDemo
   {
      public static void main(String [] args)
      {
         Employee e = null;
         try
         {
            FileInputStream fileIn =
                          new FileInputStream("employee.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            e = (Employee) in.readObject();
            in.close();
            fileIn.close();
        }catch(IOException i)
        {
            i.printStackTrace();
            return;
        }catch(ClassNotFoundException c)
        {
            System.out.println(.Employee class not found.);
            c.printStackTrace();
            return;
        }
        System.out.println("Deserialized Employee...");
        System.out.println("Name: " + e.name);
        System.out.println("Address: " + e.address);
        System.out.println("SSN: " + e.SSN);
        System.out.println("Number: " + e.number);
    }
}
于 2012-05-22T10:25:14.353 回答