【问题标题】:Java I/O how many Objects are in the file? [duplicate]Java I/O 文件中有多少个对象? [复制]
【发布时间】:2018-01-04 20:52:55
【问题描述】:

我正在尝试使用ObjectOutputStream 将人员列表保存在.txt 文件中。

public void writeUsers(List<Personnel> userList)    {
    userSize = userList.size();
    try {
        FileOutputStream fos = new FileOutputStream(userFile);
        ObjectOutputStream oos = new ObjectOutputStream(fos);

        for (Personnel user : userList){
            oos.writeObject(user);
        }
        oos.close();
        fos.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

要读取文件,我使用以下方法:

public List<Personnel> readUsers()  {
    List<Personnel> userList = new ArrayList<Personnel>();
    try {
        FileInputStream fis = new FileInputStream(userFile);
        ObjectInputStream ois = new ObjectInputStream(fis);

        for(int i = 0; i < userSize; i++){
            System.out.println("Entering loop"); 
            userList.add((Personnel)ois.readObject()); 
        }
        System.out.println(userList.size());
        ois.close();
        fis.close();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return userList;
}

我的问题是,由于writeUser()中定义的属性userSize,然后在@987654329中的循环中使用,我无法使用read方法读取现有文件而不使用writeUser()方法@。

 for(int i=0; i < userSize; i++) 

我可以做些什么来获取文件中的对象数量吗?

感谢您的宝贵时间!

【问题讨论】:

标签: java io stream


【解决方案1】:

你循环直到你得到一个 EndOfFile 异常:

while(true) {
    try {
        userList.add((Personnel) ois.readObject()); 
    } catch (EOFException e) {
         // end of file reached
    };
}

【讨论】:

    【解决方案2】:

    简单的答案:不要循环。只需将整个集合写为单个对象,然后再将其读回。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 2010-12-25
      • 2016-08-06
      • 1970-01-01
      相关资源
      最近更新 更多