0
public class Customer {
     public static void main(String[] args) throws IOException {

         FileOutputStream a = new FileOutputStream("customer.txt");
         ObjectOutputStream b = new ObjectOutputStream(a);

         human Iman = new human("Iman",5000);
         human reda = new human("reda",5555);

         b.writeObject(Iman);   //prints random symbols. 
         b.writeObject(reda);     
    }
}

class human implements Serializable{
        private String name;
        private double balance;

        public human(String n,double b){
            this.name=n;
            this.balance=b;
        }
}

これらのランダムなシンボルは何を表していますか?

4

4 に答える 4

3

Yes, you are trying to store the object itself and hence binary format is getting stored.

To actually store the data in text format, use below code BufferedWriter as below:

public void writeHumanStateToFile(Human human){
          try{
            File file = new File("filename.txt");


            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);

            bw.write(human.getName);
            bw.write(human.getBalance);
            bw.newLine();
            bw.close();
           }catch(IOException ex){
                ex.printStackTrace();
           }
       }

I am assuming you want to persist the state of Human object.

于 2013-06-21T14:12:02.057 に答える
2

データ形式は、Object Serialization Stream Protocolドキュメントで説明されています。あなたが指摘したように、それは人間が読めるものではありません。

読み取り可能な形式でシリアライズしたい場合はjava.beans.XMLEncoder、またはPojomaticのようなものを使用できる場合があります。

于 2013-06-21T14:32:27.137 に答える