如何在java中存储和读取对象的数组列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3433458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:45:34  来源:igfitidea点击:

How to store and read an array list of objects in java?

javaarraylistobjectoutputstreamobjectinputstream

提问by Nikola

I am having difficulties w/ writing and reading an array of objects from a file.

我在从文件中写入和读取对象数组时遇到困难。

This is how my object looks like:

这是我的对象的样子:

package registar;

import java.io.Serializable;

public class Vozilo implements Serializable {

    private static final long serialVersionUID = -5302010108271068350L;

    private String registracija;
    private String marka;
    private String kategorija;
    private int kubikaza;

    public Vozilo(String registracija, String marka, String kategorija,
            int kubikaza) {
        super();
        this.registracija = registracija;
        this.marka = marka;
        this.kategorija = kategorija;
        this.kubikaza = kubikaza;
    }
/* ALL GETTERS AND SETTERS ARE BELOW */

I am using basic GUI elements to get input and store it as object into a file...

我正在使用基本的 GUI 元素来获取输入并将其作为对象存储到文件中...

I'm using the following code to write to a file named "test.dat" w/ dependable flag:

我正在使用以下代码写入带有可靠标志的名为“test.dat”的文件:

final ObjectOutputStream fos = new ObjectOutputStream(new FileOutputStream("test.dat", true));

Vozilo novo = new Vozilo(txtRegistracija.getText(), txtMarka.getText(), cbKat.getSelectedItem().toString(), Integer.parseInt(txtKubikaza.getText()) );

try {
    fos.writeObject(novo);
    fos.close();
    JOptionPane.showMessageDialog(unos, "Car was added!");
} catch (IOException e) {
    e.printStackTrace();
    JOptionPane.showMessageDialog(unos, "Car was NOT added!");
}

And the following code to read from file:

以及从文件中读取的以下代码:

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.dat"));

ArrayList<Vozilo> list = new ArrayList<Vozilo>();
Vozilo vozilo = (Vozilo) ois.readObject();

list.add(vozilo);
ois.close();

for (Vozilo voz : list) {
    System.out.println("Marka: " + voz.getMarka() + "\n");
}

The problem is that I am unable to read all of the objects from file, only the first one is shown, and it iver returns IndexOutOfBounds exception :\ What am I doing wrong?

问题是我无法从文件中读取所有对象,只显示第一个对象,并且它返回 IndexOutOfBounds 异常:\ 我做错了什么?

P.S. If the solution is obvious, don't bother, I haven't slept for more than 24hrs :P

PS如果解决方案很明显,请不要打扰,我已经超过24小时没有睡觉了:P

Thank you in advance!!! Nikola

先感谢您!!!尼古拉

采纳答案by npinti

You are only reading the first object you put in the file since this:

您只是在读取您放入文件中的第一个对象,因为:

Vozilo vozilo = (Vozilo) ois.readObject();

is not in a loop.

不在循环中。

What you could do is maybe to write the entire list as one object to the file and then read it back, instead of writing and reading one object at a time.

您可以做的是将整个列表作为一个对象写入文件,然后将其读回,而不是一次写入和读取一个对象。

回答by Javid Jamae

The code you show doesn't have a loop around the readObject call, so it would only read the first object. If that's not the problem, then please post the actual code that is not working.

您显示的代码没有围绕 readObject 调用的循环,因此它只会读取第一个对象。如果这不是问题,那么请发布不起作用的实际代码。

回答by Andy Lin

You can add a loop as follows:

您可以按如下方式添加循环:

Object obj = null;
while ((obj = ois.readObject()) != null) {
    if (obj instanceof Vozilo) {
    Vozilo vozilo = (Vozilo) obj;
    list.add(vozilo);
    }
}

However, you need to deal with EOFException when it reaches the end of the file.

但是,当它到达文件末尾时,您需要处理 EOFException。

PS: please use close() in finally block :)

PS:请在 finally 块中使用 close() :)

回答by user207421

You are attempting the impossible. You can't append objects to a file with an ObjectOutputStream and get them back again, because ObjectOutputStreams have headers that won't be understood when you read the file back, unless you can organize to know where the boundaries between appends are and create a new ObjectInputStream each time as appropriate. In general this is infeasible un;ess you have a supplementary index for the file, in whcih case you might as well using blobs in a dataase. You could read the file in and write out a new one with all the original objects plus the new one each time, or better still keep the file open while you still have objects to write, if possible.

你正在尝试不可能的事情。您无法使用 ObjectOutputStream 将对象追加到文件中并再次取回它们,因为 ObjectOutputStreams 具有在您读回文件时无法理解的标头,除非您可以组织以了解追加之间的边界在哪里并创建一个每次都根据需要创建新的 ObjectInputStream。一般来说,这是不可行的,除非您有文件的补充索引,在这种情况下,您不妨在数据酶中使用 blob。您可以读入文件并每次写出一个包含所有原始对象和新对象的新文件,或者最好在仍有对象要写入的情况下保持文件打开,如果可能的话。

回答by Amrit Singh

You are only reading the first object. So you need a loop in which you can keep reading from the reader(using readObjectmethod) till it reaches the end.

您只是在阅读第一个对象。所以你需要一个循环,在这个循环中你可以继续从阅读器(使用readObject方法)读取直到它到达结束。

Object obj = null;
while ((obj = inputReader.readObject()) != null) {
    if (obj instanceof Indexing) {
    Indexing newObject = (Indexing) obj;
    list.add(newObject);
    }
}