繁体   English   中英

如何将文件中的对象添加到 ArrayList? 获得 EOFException

[英]How can I add the objects from a file into ArrayList? getting a EOFException

我正在从事一个基本上允许用户创建、编辑和显示学生的学校项目。 我有一个createStudent() ,它使用ScannerObjectOutputStream将信息写入文件。 displayStudent()使用ObjectInputStream从文件中读取数据并显示出来。 editStudent()的想法是要求用户输入他们想要编辑的学生的 ID,然后更改日期并将其写回文件,我一直在尝试做的是使用从文件中读取数据ObjectInputStream然后将该数据分配给ArrayListHashMap ,我想我将使用 ArrayList 因为 Z063A5ZBC470661C7C179 当我尝试将文件中的数据添加到 ArrayList 中时,出现以下错误:

java.io.EOFException at java.base/java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:3231) at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1663) at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:519) at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:477) at MidTermProject.editStudent(MidTermProject.java:194) at MidTermProject.main(MidTermProject.java:381)这是我的editStudent()代码:

public static void editStudent() throws IOException {
        
        int editID;
        String student;
        ArrayList<String> studentEdit = new ArrayList<String>();
        
        Scanner keyboard = new Scanner(System.in);
        
        FileInputStream fstream = new FileInputStream("studentInfo.dat");
        ObjectInputStream inputFile = new ObjectInputStream(fstream);
        
        System.out.print("Enter the ID of the student you would like to edit: ");
        editID = keyboard.nextInt();
        
        try {
            student = (String) inputFile.readObject();
            studentEdit.add(student);
            System.out.print(studentEdit);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
///Added create student method
public static void createStudent() throws IOException {
        
        File file = new File("studentInfo.dat");
        boolean append = file.exists();
        
        Scanner keyboard = new Scanner(System.in);
            
        try (
                FileOutputStream fout = new FileOutputStream(file, append);
                MidTermProject oout = new MidTermProject(fout, append);
            ) {
            id = idGenerator.getAndIncrement();
            String convertedId = Integer.toString(getId());
            oout.writeObject(convertedId);
                
            System.out.print("\nPlease enter your information bellow.\n" + "\nFull Name: ");
            FullName = keyboard.nextLine();
            oout.writeObject(FullName);
                
            System.out.print("Address: ");
            address = keyboard.nextLine();
            oout.writeObject(address);
                
            System.out.print("City: ");
            city = keyboard.nextLine();
            oout.writeObject(city);
                
            System.out.print("State: ");
            state = keyboard.nextLine();
            oout.writeObject(state);
            
            oout.close();
            System.out.println("Done!\n");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }

这是 MidTermProject 的 class 代码

public class MidTermProject  extends ObjectOutputStream {

    private boolean append;
    private boolean initialized;
    private DataOutputStream dout;
    static AtomicInteger idGenerator = new AtomicInteger(0001);
    static int id;
    public static String FullName;
    public static String address;
    public static String city;
    public static String state;
    public static String className;
    public static String instructor;
    public static String department;
    public static String classNumber;
    public static String courseNumber;
    public static String year;
    public static String semester;
    public static String grade;
    public static String studentID;
    public static String courseID;
    public static String enrollmentID;
    
    public static HashMap<String, Integer> map = new HashMap<>();
    
    Scanner keyboard = new Scanner(System.in);
    
    protected MidTermProject(boolean append) throws IOException, SecurityException {
        super();
        this.append = append;
        this.initialized = true;
    }
    
    public MidTermProject(OutputStream out, boolean append) throws IOException {
        super(out);
        this.append = append;
        this.initialized = true;
        this.dout = new DataOutputStream(out);
        this.writeStreamHeader();
    }
    
    @Override
    protected void writeStreamHeader() throws IOException {
        if (!this.initialized || this.append) return;
        if (dout != null) {
            dout.writeShort(STREAM_MAGIC);
            dout.writeShort(STREAM_VERSION);
        }
    }

如果认为您在滥用序列化:序列化是好是坏是另一回事,但这应该是这样的:

List<Student> students = ... ; 
try (OuputStream os = Files.newOutputStream(Paths.get("out"));
     ObjectOutputStream oos = new ObjectOutputStream(os)) {
  oos.writeObject(students);
}

阅读它应该很简单

try (InputStream is = Files.newInputStream(Paths.get("out"));
     ObjectInputStream iis = new ObjectInputStream(is)) {
  List<Student> students = iis.readObject(students);
}

您必须确保Student是可Serializable的并且只有可Serializable或瞬态字段:

class Student implements Serializable {
  private static final long serialVersionUID  = 1L;
  private long id;
  private String fullName;
  private String address;
  private transient String wontBeExported;
  ...
}

请注意,这些字段不是static:序列化是关于序列化 object 及其字段。 Static 字段不属于任何实例。

您也不必扩展ObjectOutputStream class,或者如果您这样做,您必须确保您阅读由您的ObjectOutputStream实现编写的 object 与您正在使用的ObjectInputStream对称

  • 如果你写一个 header,你的ObjectInputStream必须读到 header。
  • 如果你写一个 object,你的ObjectInputStream必须读到 object。

顺序很重要:在读取 header 之前,您无法读取 object。

You should also read the Java tutorial: https://docs.oracle.com/javase/tutorial/jndi/objects/serial.html

我们如何从 ArrayList 添加两个对象<object> ?<div id="text_translate"><p> 我最近开始研究 Java 的ArrayList class,并了解了我们如何使用ArrayList &lt;Object&gt;来保存不同 ZA2E03F2A3BC27CEZ 的元素。 然而,这个问题让我很困惑。</p><p> <a href="https://i.stack.imgur.com/8DnGI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8DnGI.png" alt="在此处输入图像描述"></a></p><p> 我在回答这个问题时的一般思维模式是,我们可以首先消除答案 A 和 B,因为编译器会抱怨在两个尚未强制转换的对象上使用+运算符。 然而,当我查看答案 C 和 D 时,在我看来它们都可以正常工作,因为它们都将从list.get()返回的值转换为定义了运算符+的类型。 这导致我选择答案 E,因为我相信 C 和 D 都可以在这段代码中工作。</p><p> 然而,正如你所看到的,E 是错误的答案。 为了使我更加困惑,我在 repl.it 上测试了这段代码,确认答案选项 A 和 B 会导致编译错误,而答案选项 C 和 D 都将正确的值9存储到i中。 所以现在,我真的很困惑。 Object是否有一些我在这里掩饰的规则? 有人可以指出我正确的方向吗?</p></div></object>

[英]How can we add two objects from a ArrayList <Object>?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将数据从XML文件添加到ArrayList 如何向文件添加对象的数组列表 我如何使用ArrayList中的对象以能够从存储Java的其他位添加或删除它们 我们如何从 ArrayList 添加两个对象<object> ?<div id="text_translate"><p> 我最近开始研究 Java 的ArrayList class,并了解了我们如何使用ArrayList &lt;Object&gt;来保存不同 ZA2E03F2A3BC27CEZ 的元素。 然而,这个问题让我很困惑。</p><p> <a href="https://i.stack.imgur.com/8DnGI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8DnGI.png" alt="在此处输入图像描述"></a></p><p> 我在回答这个问题时的一般思维模式是,我们可以首先消除答案 A 和 B,因为编译器会抱怨在两个尚未强制转换的对象上使用+运算符。 然而,当我查看答案 C 和 D 时,在我看来它们都可以正常工作,因为它们都将从list.get()返回的值转换为定义了运算符+的类型。 这导致我选择答案 E,因为我相信 C 和 D 都可以在这段代码中工作。</p><p> 然而,正如你所看到的,E 是错误的答案。 为了使我更加困惑,我在 repl.it 上测试了这段代码,确认答案选项 A 和 B 会导致编译错误,而答案选项 C 和 D 都将正确的值9存储到i中。 所以现在,我真的很困惑。 Object是否有一些我在这里掩饰的规则? 有人可以指出我正确的方向吗?</p></div></object> 在for循环中使用此ArrayList时如何将对象添加到ArrayList中? 如何在不获取EOFException的情况下确定文件是否为空 如何在文件中读写对象的数组列表的数组列表? 如何从对象数组列表中删除项目? 如何从数组列表读取和写入对象? 如何将其添加到数组列表中?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM