我正在用 Java 编写服务器/客户端应用程序。我在服务器端做一些数据处理,然后将其存储在 HashMap
中。将 HashMap
传递给客户端的最佳方式是什么?
最佳答案
最直接的解决方案是使用 ObjectOutputStream
和 ObjectInputStream
对其进行序列化/反序列化
try {
...
final Map<A, B> yourMap = ...; // Map to send
final OutputStream yourOutputStream = ...; // OutputStream where to send the map in case of network you get it from the Socket instance.
final ObjectOutputStream mapOutputStream = new ObjectOutputStream(yourOutputStream);
mapOutputStream.writeObject(yourMap);
...
} finally {
outputStream.close();
}
并接收它:
try {
...
final InputStream yourInputStream = ...; // InputStream from where to receive the map, in case of network you get it from the Socket instance.
final ObjectInputStream mapInputStream = new ObjectInputStream(yourInputStream);
final Map<A, B> yourMap = (Map) mapInputStream.readObject();
...
} finally {
mapInputStream.close();
}
请注意,这不需要任何外部库。
关于java - 在 java 中序列化一个 HashMap 以将它从服务器传递到 java 中的客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20199493/