次の方法を使用して .ser ファイルに書き込むことができます。
try {
FileOutputStream fos = new FileOutputStream("Filename.ser");
ObjectOutputStream out = new ObjectOutputStream(fos);
out.write(obj);
fos.close();
out.close();
} catch (IOException ex) {}
更新サーバー側でオブジェクトを読み取るには、クライアントと対話するソケットの inputStream をラップ
して作成する必要があります。ObjectInputStream
次のように実行できます。
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){}
}
}
}
}