【问题标题】:Appendable Binary File附加二进制文件
【发布时间】:2020-10-07 16:42:47
【问题描述】:

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

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

我在尝试打开二进制文件时遇到错误(java.io.StreamCorruptedException: invalid stream header: 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();
  }

更新: 当前要读取的代码,但它没有在屏幕上打印任何内容:

try(ObjectInputStream ois = new ObjectInputStream(
                        new BufferedInputStream(Files.newInputStream(f))))
 {
            while (ois.available() > 0) 
            {

                    st = (Student) ois.readObject();
                    studentlist.addAccount(st);
                    System.out.println(st.getStudentNumber());
                }

            }

 catch (Exception ex) 
                {
                    ex.printStackTrace();
                }

这是我写入文件的方式:

Path f = Paths.get("person.dat");

   try (ObjectOutputStream oos = new ObjectOutputStream(
           new BufferedOutputStream(Files.newOutputStream(f, StandardOpenOption.APPEND))))
   {
       oos.writeObject(new Student(name,age));    
   }
   catch(Exception ex)
   {
       ex.printStackTrace();
   }

【问题讨论】:

    标签: java file stream binary append


    【解决方案1】:

    我建议使用 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
        }
    

    并读取文件,例如(未经测试):

        List<Student> students = new ArrayList<>();
        try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(personDataFilePath)))){
            while (ois.available() > 0){
                students.add((Student) ois.readObject());
            }
        } catch (IOException ex) {
            // do some error handling here
        }
    

    【讨论】:

    • 我如何将它放入一个循环中以读取文件中的所有对象直到文件结束?我尝试了各种方法,要么在第一个对象处获得无限循环,要么得到无效代码 AC 错误。
    • @user13764634 请注意,对象流不是一种非常好的(稳定)格式来保存数据。考虑使用例如数据库(例如,使用 H2 和 JPA/Hibernate)、JSON(uisng Jackson)或 XML(使用 JAXB)。
    • @user13764634 你到底尝试了什么。有没有用InputStream.availbale()的方法检查是否还有更多数据?
    • 感谢您的回复!真的很感激。我已经更新了上面的代码。我正在通过在屏幕上打印来测试它的阅读方式,但现在什么也没有出现。
    【解决方案2】:

    我已修改代码以解决使文件“可附加”的问题。我将一个 arraylist 对象写入文件(arraylist 包含一个学生对象列表)。当我想添加一个学生时,我从文件中读取对象(arraylist),将我的新学生添加到 arraylist 并将 arraylist 写回文件。它现在可以工作了,我的文件没有附加格式。

    【讨论】:

      猜你喜欢
      • 2017-05-12
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      • 1970-01-01
      • 2011-10-13
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多