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

是的,您正在尝试存储对象本身,因此正在存储二进制格式。

要以文本格式实际存储数据,请使用以下代码 BufferedWriter,如下所示:

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();
           }
       }

我假设您想保持 Human 对象的状态。

于 2013-06-21T14:12:02.057 回答
2

数据格式在对象序列化流协议文档中进行了描述。正如您所指出的,它不是人类可读的。

如果你想以可读的格式序列化,你可以使用java.beans.XMLEncoder,或类似Pojomatic的东西。

于 2013-06-21T14:32:27.137 回答
2

你正在使用ObjectOutputStream. 这不会产生文本 - 它会产生数据的二进制序列化版本。如果您确实需要文本表示,则需要使用不同的方法。

如果您对它是二进制数据感到满意,请保持原样 - 但可能会更改文件名以减少误导。您可以使用 再次读取数据ObjectInputStream

于 2013-06-21T14:04:14.677 回答
1

您正在序列化对象。它并不是要以纯文本形式阅读,而是一种二进制格式,可以轻松读取对象并在以后的程序执行中重新创建它。

如果要以纯文本形式存储对象,则需要将对象的各个字段写入文件。

于 2013-06-21T14:03:46.697 回答