简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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