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

发布于 2024-09-13 12:18:11 字数 1752 浏览 3 评论 0原文

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

这就是我的对象的样子:

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 */

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

我正在使用以下代码写入名为“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!");
}

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

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");
}

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

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

提前谢谢您! 尼古拉

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...

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

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?

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

Thank you in advance!!!
Nikola

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

忘年祭陌 2024-09-20 12:18:11

您仅读取放入文件中的第一个对象,因为 this:

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

不在循环中。

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

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.

浴红衣 2024-09-20 12:18:11

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

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

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

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

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.

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

泪眸﹌ 2024-09-20 12:18:11

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

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.

无尽的现实 2024-09-20 12:18:11

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

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.

舂唻埖巳落 2024-09-20 12:18:11

您只阅读第一个对象。因此,您需要一个循环,您可以在其中继续从阅读器读取内容(使用 readObject 方法)直到到达末尾。

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

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

Object obj = null;
while ((obj = inputReader.readObject()) != null) {
    if (obj instanceof Indexing) {
    Indexing newObject = (Indexing) obj;
    list.add(newObject);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文