在java

时间:2016-07-12 17:16:11

标签: java file serialization stream

这是我的Person类

package com.igate.serilaization;

import java.io.Serializable;

public class Person implements Serializable {

    private String name;
    private int age;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    public Person(String name , int age){
        this.name=name;
        this.age= age;
    }


}

这是我的主要课程

package com.igate.serilaization;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.ObjectOutputStream;


public class Serilalizer2 {

    public static void main(String[] args) {

        Person p = new Person("Prasad", 18);

        try {
            FileInputStream fout = new FileInputStream("C:/Users/pmadge/Desktop/serial.ser");
            ObjectOutputStream o = new ObjectOutputStream(fout);
            o.writeObject(p);
            o.close();
            System.out.println("Done");


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }



}

我在`ObjectOutputStream o = new ObjectOutputStream(fout)上遇到编译错误;像“构造函数ObjectOutputStream(FileInputStream)未定义”这样的行。

1 个答案:

答案 0 :(得分:3)

您应该使用FileOutputStream代替FileInputStream

<强>代码

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;


public class Serializer2 {

    public static void main(String[] args) {

        Person p = new Person("Prasad", 18);

        try {
            FileOutputStream fout = new FileOutputStream ("C:/Users/pmadge/Desktop/serial.ser");
            ObjectOutputStream o = new ObjectOutputStream(fout);
            o.writeObject(p);
            o.close();
            System.out.println("Done");


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }



}

我希望这会对你有所帮助。