简体   繁体   English

将对象写入文件

[英]Write/Read object to file

I'm trying to read/write an object to a file, and came up with this code, which I have edited, but when I open the file it appears weird characters and signs, I guess thats the Serializable stuff in there. 我试图将对象读/写到文件中,并想出了我编辑过的代码,但是当我打开文件时,它出现了奇怪的字符和符号,我想那是其中的可序列化的东西。 Is there any way to write it properly? 有什么办法可以正确编写吗? That is my code so far. 到目前为止,这是我的代码。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;


public class Controlador_Dades_Doctor 
{
    public void escriureFitxer(Doctor doctor){

        ObjectOutputStream out;
        try {
            File file = new File("Doctors.ser");
            out = new ObjectOutputStream(new FileOutputStream(file));
            out.writeObject(doctor);

            out.flush();
            out.close();
            System.out.println("Object written to file");
        }
        catch (FileNotFoundException ex) {
            System.out.println("Error with specified file") ;
            ex.printStackTrace();
        }
        catch (IOException ex) {
            System.out.println("Error with I/O processes") ;
            ex.printStackTrace();
        }             
    }
}

Thats my output file, as you can see it has strange characters. 多数民众赞成在我的输出文件,如您所见,它具有奇怪的字符。

¬í sr DoctorÑmçUÝâ& I idI num_guardiesD souL nomt Ljava/lang/String;xp      @—p     t rux

Also, I've got another class which is a Map of this first class, I've got no clue how I could write them to a file aswell, so a file would contain my Doctor Map. 另外,我还有另一个类,它是此类的Map。我不知道如何将它们也写到文件中,因此文件将包含Doctor Map。 Thanks in advance! 提前致谢!

"Write it properly". “写正确”。 This is what Serialize is supposed to do. 这就是序列化应该做的。 There is nothing wrong with what it is doing. 它所做的没有错。 If you want to read that same object you deserialize the file and recreate the object. 如果要读取同一对象,请反序列化文件并重新创建该对象。 If you want human readable file with objects data then you should create your own method for writing the object data to a .txt file and format it how you want. 如果您希望使用带有对象数据的人类可读文件,则应创建自己的方法将对象数据写入.txt文件并按照所需的格式对其进行格式化。

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

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