简体   繁体   English

无法从文件读取多个对象

[英]Can't read multiple objects from a file

I'm trying to put the (Lieu) objects into an ArrayList but but at the end of the code, my list is still empty. 我正在尝试将(Lieu)对象放入ArrayList ,但是在代码末尾,我的列表仍然为空。 I've been looking on the net for an answer but all I find is "Write your objects in a collection then read the collection". 我一直在网上寻找答案,但是我发现的只是“在集合中写入对象,然后阅读集合”。 But the file is already written and i need to find a way to put all the (Lieu) objects in a ArrayList. 但是文件已经被写入,我需要找到一种将所有(Lieu)对象放入ArrayList中的方法。

Here's the writing Code (I can't modify it): 这是写作代码(我无法修改):

public static void main(String[] args) {
        Lieu<Double, String> p1;
        Lieu<Double, String> p2;
        Lieu<Double, String> p3;
        SegmentGeo<String> e1;
        SegmentGeo<String> e2;
        SegmentGeo<String> e3;
        Parcelle<String> p = new Parcelle<String>();
        ArrayList<Mesure<Point<Double>, String>> segs;
        p1 = new Lieu<Double, String>(45.573715, -73.900295, "p1");
        p2 = new Lieu<Double, String>(45.573882, -73.899748, "p2");
        p3 = new Lieu<Double, String>(45.574438, -73.900099, "p3");
        e1 = new SegmentGeo<String>(p1, p2, "Parcelle test");
        e2 = new SegmentGeo<String>(p2, p3, "Parcelle test");
        e3 = new SegmentGeo<String>(p3, p1, "Parcelle test");
        segs = new ArrayList<Mesure<Point<Double>, String>>();
        segs.add(e1);
        segs.add(e2);
        segs.add(e3);
        try {
            p.setMesures(segs);
        } catch (TrajectoireNonValideException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ObjectOutputStream ois = null;
        try {
            ois = new ObjectOutputStream(new FileOutputStream("essai.txt"));
            ois.writeObject(p.informationCumulee());
            ois.writeObject(p1);
            ois.writeObject(p2);
            ois.writeObject(p3);
        } catch (EOFException ex) {
            System.out.println("Fin de fichier atteinte.");
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (ois != null) {
                    ois.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

And here's what I'm trying to do: 这就是我想要做的:

public void actionPerformed(ActionEvent arg0) {
    JFileChooser chooser = new JFileChooser();
    int retour = chooser.showOpenDialog(getParent());
    if(retour==JFileChooser.APPROVE_OPTION){
          try{
       FileInputStream fis = new FileInputStream(chooser.getSelectedFile().getName());
       ObjectInputStream ois = new ObjectInputStream(fis);
       champNom.setText((String) ois.readObject());//that's just to display the name
       while (ois.available()!=0) 
       { 
            temp = (Lieu)ois.readObject();
            l.add(temp);
       }
       ois.close();
       System.out.print(l.size());//The size is 0
       }
       catch (FileNotFoundException e) {
           e.printStackTrace();
       }
       catch (IOException e) {
           e.printStackTrace();
       } 
       catch (ClassNotFoundException e) {
           e.printStackTrace();
       }
     }

As Joetjah says, available() doesn't work like it sounds like. 正如Joetjah所说, available()不能像听起来那样工作。

One solution that is not super elegant but works surprisingly well is to just catch the Exception s which will be thrown when there is nothing left to read or another exception, as such: 一种不是超级优雅但效果出奇的解决方案是仅捕获Exception ,当没有内容可读取或出现其他异常时将抛出Exception ,例如:

    try {
        while (true)
            l.add((Lieu<Double,String>)ois.readObject());
    } catch (ClassNotFoundException | IOException e) {
        //Expecting a EOFException here
    } finally {
        try {
            ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Whenever there's an exception is thrown when reading (and at some point there will be one!), it will stop reading. 只要在读取时抛出异常(并且在某个时候会发生异常!),它将停止读取。

Available doesn't do what you think it does 可用功能无法执行您认为的操作

available() does not return the amount of data left to be read, but the amount of data that can be read without blocking (pausing to wait for more data from the file/socket/database/etc.). available()不会返回剩余要读取的数据量,而是可以读取而不会阻塞的数据量(暂停以等待来自文件/套接字/数据库/等的更多数据)。 In some cases this may return zero while there are still bytes that should be read - the 0 means that there are 0 bytes available right now (with no blocking). 在某些情况下,当仍有字节需要读取时,它可能返回零-0表示当前有0字节可用(无阻塞)。 This may happen for various reasons - a hard drive may be busy repositioning its magnetic reader, or a network connection may be busy, or perhaps you're waiting for a user somewhere to type something before their information may be sent. 发生这种情况的原因可能多种多样-硬盘驱动器可能正在忙于重新定位其磁读取器,或者网络连接正在忙碌,或者您可能正在等待用户在某处键入某些内容,然后才能发送其信息。 Or it may be because the file you're reading really has no additional bytes to read, because you've reached the end. 或可能是因为您要读取的文件确实没有其他字节要读取,因为您已经到达末尾。 Using available() you have no way of knowing whether or not you should try to read the bytes anyway. 使用available(),您无法知道是否应该尝试读取字节。

A more correct way to use a stream to copy a file is to check the return value of read for the end-of-file value (-1): 使用流复制文件的更正确方法是检查read的返回值是否为文件结尾值(-1):

InputStream is = // some input
OutputStream os = // some output
byte buffer = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {   
   os.write(buffer, 0, bytesRead);
}

When this code completes, you know that all the bytes really have been read and copied, because the while loop doesn't complete until read() returns -1, indicating the end of input. 这段代码完成后,您知道所有字节都已被真正读取并复制,因为while循环直到read()返回-1(表示输入结束)后才完成。

Now, in your case, I'd advice to take it to some other direction, like this: 现在,就您的情况而言,我建议您将其转到其他方向,例如:

FileInputStream fis = new FileInputStream(chooser.getSelectedFile().getName());
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj = ois.readObject();
while (obj != null) 
{ 
    champNom.setText((String)obj); 

    if (obj instanceof Lieu<Double, String>) 
        l.add(obj);

    obj = ois.readObject();
}
ois.close();
System.out.print(l.size());

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

相关问题 无法从文件读取对象并将其放置到Java中的链表 - Can't read objects from file and place them to linkedlist in java Java从文件中读取多个对象 - Java read multiple objects from a file 如何从文件中读取多个相同的对象 - How to read multiple same objects from a file Android:无法将从文件读取的数据传递给多个类 - Android: Can't Pass Data Read From File To Multiple Classes 无法从使用对象输出流写入的文件中读取对象属性 - Can't read objects properties from file written by using object output stream 我无法从文件中读取其他对象:java.io.streamcorruptedexception:无效类型代码:ac - I can't read the other objects from file: java.io.streamcorruptedexception: invalid type code: ac 无法将txt文件读入对象数组然后打印出结果 - Can't read the txt file in to an array of objects and then print out the result FileInputStream和OutputStream无法读取对象并将其写入文件 - FileInputStream and OutputStream can't read and write objects into file 如何从 Java 中的单个文件读取多个 JSON 对象? - How to read multiple JSON objects from a single file in Java? 如何从文本文件中读取多个对象,然后发送到 ArrayList? - How to read multiple objects from a text file and then send to an ArrayList?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM