附加二进制文件

问题描述 投票:1回答:1

我正在将对象附加到二进制文件。我的文件是:

File f=new File("person.dat");

当我尝试打开二进制文件时,出现错误(java.io.StreamCorruptedException:无效的流头:79737200)。据我所知,程序可以很好地写入数据,但是当我尝试从中读取数据时,就会出现上述错误。任何帮助表示赞赏!

我要写的代码:

AppendObjectOutputStream out = null;

try {
    out = new AppendObjectOutputStream(new FileOutputStream(f, true));
    out.writeObject(new Student(name, age));
    out.flush();

     } 
catch (Exception ex) {
    ex.printStackTrace();
     } 
 finally {
    out.close();
     }

我的可追加类:

public class AppendObjectOutputStream extends ObjectOutputStream {

    public AppendObjectOutputStream(OutputStream out) throws IOException {
        super(out);
    }

    @Override
    protected void writeStreamHeader() throws IOException {
        reset();
    }
 }

我用于读取对象并将其添加到ArrayList的部分代码:

Course course = new Course();
Student st = null;
ObjectInputStream in = null;
try {
    in = new ObjectInputStream(new FileInputStream("person.dat"));

    try 
      {
        while (true) 
         {
            st = (Student) in.readObject();
            course.addAccount(st); //adds student object to an ArrayList in 
                                   //class Course
          }
      } 
    catch (EOFException ex) {
    }
  } 
  catch (Exception ex) {
    ex.printStackTrace();
  } finally {
    in.close();
  }
java file stream binary append
1个回答
0
投票

而不是尝试修复实用程序类,我建议使用NIO.2 File API的标准类。

尝试类似(未经测试):

    Path personDataFilePath = Paths.get("person.dat");
    // or Java 11:
    // Path personDataFilePath = Path.of("person.dat");
    try (ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(Files.newOutputStream(personDataFilePath, StandardOpenOption.APPEND)))){
        oos.writeObject(new Student(name,age));
    } catch (IOException ex) {
        // do some error handling here
    }

并读取文件,类似(未测试):

    try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(personDataFilePath)))){
        Student st = (Student) ois.readObject();
    } catch (IOException ex) {
        // do some error handling here
    }
© www.soinside.com 2019 - 2024. All rights reserved.