1

这是我的清单:

List<Form> to_be_sent=new ArrayList<Form>();

Form 是一个实现可序列化的类,只包含字符串字段。
我可以这样做吗:

ObjectOutputStream writer = new ObjectOutputStream(resp.getOutputStream());
writer.writeObject(to_be_sent);
writer.close();
4

1 回答 1

1

有用!

这是一个最小的工作实现,它序列化一个 List,并通过套接字连接发送它并在另一端反序列化它,打印到达的内容。

public static void main(String[] args) throws Exception {
    List<String> list = Arrays.asList("one", "two", "three");
    Thread serverThread = new Thread(new Runnable() {
        public void run() {
            try {
                InputStream in = new ServerSocket(999).accept().getInputStream();
                Object object = new ObjectInputStream(in).readObject();
                System.out.println(object.getClass() + ": " + object);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    serverThread.start();
    Socket socket = new Socket("localhost", 999);
    new ObjectOutputStream(socket.getOutputStream()).writeObject(list);
    serverThread.join();
}

输出:

class java.util.Arrays$ArrayList: [one, two, three]
于 2012-05-05T11:23:16.583 回答