java - 从文件中读取多个对象,就像它们在数组中一样 [英] java - Reading multiple objects from a file, as they were in an array

查看:67
本文介绍了java - 从文件中读取多个对象,就像它们在数组中一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问社区,您对以下情况有何看法.任务是将对象写入文件.这可以通过将对象列表写入文件来实现,稍后我可以读取该文件,以便我再次拥有我的对象.在这里,我实际上只会将一个对象写入文件,即列表(可能包含更多对象).

I would like to ask the community what do you think about the following situation. The task is to write objects to a file. Which could be made by writing a list of objects to the file that I can read later so I have my objects again. Here, I would write practically ONLY ONE object to the file, namely the list (that may contain more objects).

但是,任务接缝是将单独的对象写入文件,该方法从列表中接收该文件.对象可以是任何东西.(当然它们必须是可序列化的)

But, the task seams to be to write separate objects to the file, which the method receives from a list. The objects can be whatever. (they must be serializable of course)

所以我做到了:

public class TaskStream {
    public static void saveObjects(ArrayList<Object> al) {
        try {
            FileOutputStream fos = new FileOutputStream("outputFile", true);
            try {
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                for (Object o : al){
                    try {
                        oos.writeObject(o);
                        System.out.println("saved");
                    } catch (NotSerializableException e) {
                        System.out.println("An object was not serializable, it has not been saved.");
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

这很好用.

但是现在,我想阅读它们.我关于它的第一个概念是一种方法,它读取对象直到文件中有对象,然后我可以将它们中的每一个再次保存到列表中(这就是任务).所以像伪代码:

But now, I'd like to read them. My first concept about it would be a kind of method, that reads objects until the file has objects, and I can save each of them to a list again (that's the task). So like Pseudo code:

for(Object o : fileToRead){ list.add(o) }

怎么可能?我开始玩弄ObjectInputStream的readObject方法,但似乎导致了很多错误.

How would it be possible? I started to play around with the readObject method of the ObjectInputStream, but it seems to lead to a lot of errors.

你有什么想法吗?或者这样的任务的最佳实践是什么?

Do you have any idea? Or what would be the best practice by such a task?

谢谢!

我尝试了你的想法.确切的实现:

I tried your idea. The exact implementation:

public static ArrayList<Object> readObjects(){
    ArrayList<Object> al = new ArrayList<Object>();
    boolean cont = true;
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("outputFile"));
            while(cont){
                  Object obj=null;
                try {
                    obj = ois.readObject();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                  if(obj != null)
                     al.add(obj);
                  else
                     cont = false;
               }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

 return al;
}    

为了测试程序,我将向文件中写入两个对象.我从文件中读取对象并将它们添加到列表中.我遍历这个列表并打印出内容.

To test the program I will write two objects into the file. I read the objects from the file and add them to a list. I iterate through this list and print out the content.

如果我运行程序,会发生以下情况(我删除了 outputFile,所以程序可以重新创建它并从头开始做所有事情).

If I run the program the following happens (I deleted the outputFile, so the program can recreate it and do everything from scratch).

结果:

列表中的两个对象将被成功打印.但我收到了这个:

The two objects from the list will be successfully printed. But I receive this:

java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2598)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1318)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)    

...

我没有改变任何东西,我再次运行程序.结果:

I don't change anything, and I run the program again. Result:

列表中的两个对象将被成功打印.但我收到了这个:

The two objects from the list will be successfully printed. But I receive this:

java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1377)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)    

从现在开始,任何重新运行都会带来相同的结果.

From now on, any rerun brings the same result.

如果我从头开始重复整个过程(从删除 outputFile 开始),一切都会完全相同(如预期).

If I repeat the whole process from the very beginning again (starting by deleting the outputFile) everything happens exactly the same (as expected).

您有解决方法的想法吗?非常感谢您的帮助!

Do you have ideas how to fix it? Thank you very much for the help!

推荐答案

您将要使用 FileInputStream 和 ObjectInputStream.

You're going to want to use FileInputStream and ObjectInputStream.

FileInputStream fis = new FileInputStream("outputFile");
ArrayList<Object> objectsList = new ArrayList<>();
boolean cont = true;
while (cont) {
  try (ObjectInputStream input = new ObjectInputStream(fis)) {
    Object obj = input.readObject();
    if (obj != null) {
      objectsList.add(obj);
    } else {
      cont = false;
    }
  } catch (Exception e) {
    // System.out.println(e.printStackTrace());
  }
}

这篇关于java - 从文件中读取多个对象,就像它们在数组中一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆