Java二进制读取对象

时间:2015-12-06 16:52:12

标签: java binaryfiles

我在ArrayList中存储了一组4名学生,他们每个都有创建时生成的唯一ID。例如:[James,1],[Jone,2], [凯特,3],[杰克,4]。但是,如果我从二进制文件中读取这些对象,然后将其他Person对象添加到数组列表中,则ID将重置为0.但我想要添加新对象ID,例如:[Sam,5]。

private int id;
private static int count;

public Student(String firstName, String lastName, String phone, String address) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        id = ++count;
        this.phone = phone;
        this.address = address;
}

public void loadPersonBinary(){
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream("Person.dat");
            ois = new ObjectInputStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch(Exception ev) {
            System.out.println("Exception!");
        }
        System.out.println("Reading from the file...");
        try {
            p = (ArrayList<Person>) ois.readObject();
            //it only read once. Count always stays at 1
            int count = 0;
            Person.setCount(++count);
            System.out.println(count);
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
        } 
        try {
            ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2 个答案:

答案 0 :(得分:0)

您必须序列化您的数据:

1你必须声明public Person实现Serializable

2更好地声明版本UID(非强制性)

List< Person> the_list;
OutputStream file = new FileOutputStream( "mydatas.ser" );
OutputStream buffer = new BufferedOutputStream( file );
ObjectOutput output = new ObjectOutputStream( buffer );
output.writeObject(the_list);

3只是像你一样写

 InputStream file2 = new FileInputStream( "mydatas.ser" );
 InputStream buffer2 = new BufferedInputStream( file2 );
 ObjectInput input = new ObjectInputStream ( buffer2 );
 ArrayList< Person> lp= (ArrayList< Person>)  input.readObject();

4你可以重新加载

{{1}}

答案 1 :(得分:0)

使用ObjectOutPutStream->FileOutputStream写入文件时,必须使用不同的API进行追加。

 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.dat",true));

javadocs

查看FileOutputStream
public FileOutputStream(String name,
                boolean append)
                 throws FileNotFoundException
  

创建文件输出流以写入具有指定名称的文件。如果第二个参数为true,则字节将写入文件的末尾而不是开头。创建一个新的FileDescriptor对象来表示此文件连接。

就个人而言,我更喜欢编写List并读取对象列表而不是编写多个单独的对象。