您可以使用以下方式写入 .ser 文件:
try {
FileOutputStream fos = new FileOutputStream("Filename.ser");
ObjectOutputStream out = new ObjectOutputStream(fos);
out.write(obj);
fos.close();
out.close();
} catch (IOException ex) {}
更新
要在服务器端读取对象,您需要创建ObjectInputStream
与客户端交互的套接字的 inputStream 包装。可以按如下方式完成:
try
{
Socket s = serverSocket.accept();
ObjectInputStream oin = new ObjectInputStream(s.getInputStream());
Object obj = oin.readObject();
oin.close();
}catch(Exception ex){}
好的,这是我向服务器发送 ArrayList 的完整示例。
客户端.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Client
{
public static void main(String[] args)
{
Socket s = null;
ObjectOutputStream out = null;
System.out.println("Connecting to Server ...");
try
{
s = new Socket("localhost", 1401);
out = new ObjectOutputStream (s.getOutputStream());
ArrayList<String> list = ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < 10 ; i++)
{
list.add("String"+i);
}
out.writeObject(list);out.flush();
System.out.println("ArrayList sent to Server");
} catch ( Exception e)
{
e.printStackTrace();
}
finally
{
if (out!= null)
{
try
{
out.close();
}
catch (Exception ex){}
}
if (s != null)
{
try
{
s.close();
}
catch (Exception ex){}
}
}
}
}
服务器.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Server
{
public static void main(String[] args)
{
ObjectInputStream oin = null;
ServerSocket server;
Socket socket = null;
try
{
server = new ServerSocket(1401);
socket = server.accept();
System.out.println("Client Connected..Sending ArrayList to Client");
oin = new ObjectInputStream(socket.getInputStream());
ArrayList<String> list = (ArrayList<String>)oin.readObject();
System.out.println("Recieved ArrayList from client "+list);
//Writing to file now
FileOutputStream fos = new FileOutputStream("Filename.ser");
ObjectOutputStream out = new ObjectOutputStream(fos);
out.write(obj);
fos.close();
out.close();
System.out.println("Written to file");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if (oin != null)
{
try
{
oin.close();
}
catch (Exception ex){}
}
if (socket != null)
{
try
{
socket.close();
}
catch (Exception ex){}
}
}
}
}