【问题标题】:File Object Serialization文件对象序列化
【发布时间】:2016-04-29 20:30:26
【问题描述】:

我有一个客户端服务器程序,我需要在其中序列化文件对象并将其发送到客户端。

在服务器端:

FileInputStream input_file = new FileInputStream(file);
object_output_stream.writeObject(input_file);

在客户端:

FileOutputStream ouput_file = new FileOutputStream(new File(filename));
output_file = object_input_stream.readObject();

我需要序列化 ​​input_file 对象并将其发送给客户端。 ObjectOutputStream 和 ObjectInputStream 是不可序列化的。最好的方法是什么?

【问题讨论】:

    标签: java file serialization objectoutputstream


    【解决方案1】:

    您不能序列化文件 - 这意味着客户端可以从服务器上读取文件,这需要一个复杂的协议,而 Java 序列化机制中根本不存在这种协议。

    最好的方法是将文件中的数据读取到字节数组中,然后将字节数组直接发送到客户端,或者在 ObjectOutputStream 中序列化字节数组(如果你想这样做,你可以这样做发送其他对象)

    您可以使用 apache-commons IOUtils.toByteArray(InputStream input) 轻松将文件读入byte[]

    在服务器端:

    FileInputStream input_file = new FileInputStream(file);
    byte[] input_data = IOUtils.toByteArray(input_file);
    object_output_stream.writeObject(input_data);
    

    在客户端:

    FileOutputStream output_file = new FileOutputStream(new File(filename));
    byte[] input_data = (byte[]) object_input_stream.readObject();
    output_file.write(input_data);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-13
      • 2013-03-14
      • 1970-01-01
      相关资源
      最近更新 更多