简体   繁体   English

如何使用它们所引用的对象序列化字段?

[英]How to serialize fields with objects they are reference to?

My class Message is the class-wrapper to File. 我的班级Message是File的班级包装。 I want to serialize Message, send it on server, than deserialize and get File. 我想序列化Message,在服务器上发送,而不是反序列化并获取File。 But when i deserializing, I get only File name? 但是当我反序列化时,我只会得到文件名吗? What i am doing wrong? 我做错了什么?

Class-wrapper: 类包装:

public class Message implements Serializable{
    private int id;
    private File file;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }
}

Deserializing code: 反序列化代码:

ObjectInputStream objectInputStream = new ObjectInputStream(in);
        Message message = (Message)objectInputStream.readObject();
        objectInputStream.close();
        String fileText = "";
        FileReader fileReader = new FileReader(message.getFile());
        BufferedReader br = new BufferedReader(fileReader);
        fileText = br.readLine();

When i trying to do this, i get FileNotFoundException. 当我尝试执行此操作时,出现FileNotFoundException。 Help please. 请帮助。 Thank you. 谢谢。

A File is just an abstract representation of a file, basically the path to the actual file. File只是File的抽象表示,基本上是实际文件的路径。 You can't serialize it, send it on the network, then act like the actual bytes of the file are present. 您无法对其进行序列化,将其发送到网络上,然后像显示文件的实际字节一样操作。

You need to actually read the bytes from the file and send them over the network. 您实际上需要从文件中读取字节并通过网络发送它们。 If you're working with small files, you could probably replace File with byte[] (and possibly add the filename or other metadata) and work with that. 如果您正在处理小文件,则可以用byte[]替换File (并添加文件名或其他元数据)并进行处理。

If you're working with bigger files, you should probably consider something else than serialization, as the memory requirements become too large. 如果要处理更大的文件,则可能需要考虑序列化之外的其他事情,因为内存需求太大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM