简体   繁体   English

如何从文本文件读取到对象数组

[英]How to read from text file into array of Objects

So i looked over a couple of solutions but none of them worked for me. 因此,我查看了几个解决方案,但没有一个对我有用。 Thanks for some folks i got the infinite cycle right in the end, but it still doesnt work for me. 感谢某些人,我最终获得了无限循环,但对我来说仍然无效。 I want to read a file "output.txt" into a list of objects. 我想将文件“ output.txt”读入对象列表。 So i provide the remaining codes since i thought they wouldnt help at all... 所以我提供了剩余的代码,因为我认为它们根本无法提供帮助。

try {
            List<House> listH = new ArrayList<>();
            boolean cont = true;
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("output.txt"));
            while(cont)
            {
                House house = (House) ois.readObject();
                if(house != null)
                    listH.add(house);
                else
                    cont = false;
            }
            ois.close();
            mainmenu();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

The writing code: 编写代码:

try {
            FileWriter writer = new FileWriter("output.txt");
            for(House str : listH)
            {
                writer.write(String.valueOf(str) + "\n");
            }
            writer.close();
            System.out.println("Successful writing");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Couldn't write");
        }

The House Object: 房屋对象:

public class House {
    String address;
    double area;
    boolean garage;

    public House(String address, double area, boolean garage){
        this.address=address;
        this.area = area;
        this.garage = garage;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public double getArea() {
        return area;
    }

    public void setArea(double area) {
        this.area = area;
    }

    public boolean isGarage() {
        return garage;
    }

    public void setGarage(boolean garage) {
        this.garage = garage;
    }

    @Override
    public String toString() {
        return address + ";" + area + ";" + garage;
    }
}

The error messages are the following: 错误消息如下:

java.io.StreamCorruptedException: invalid stream header: 3134313B at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:866) at java.io.ObjectInputStream.(ObjectInputStream.java:358) java.io.StreamCorruptedException:无效的流标头:java.io.ObjectInputStream。(ObjectInputStream.java:358)上的java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:866)处为3134313B

You have three main problems: 您有三个主要问题:

  1. Your while loop is infinite and may cause a stackoverflow error, make the condition check that there is another line/object to be read in the file before it proceeds. 您的while循环是无限的,可能会导致stackoverflow错误,请在继续执行条件之前检查文件中是否有其他行/对象要读取。
  2. The code that reads the file casts directly to a House object, this highly dependent on format of the file writing, any error will cause a failed read. 读取文件的代码直接投射到House对象,这在很大程度上取决于文件写入的格式,任何错误都将导致读取失败。
  3. The else part of the condition checking if house is null breaks out of the whole reading process, so if there is one null house for any reason all houses after it will not be read For a more specific answer I may need House class structure and the process used to create the output file.Otherwise use hasnext in the while condition and readline to 'manually' construct a house object from string values. 条件检查的其他部分将检查是否为空,这将打破整个阅读过程,因此,如果由于某种原因而存在一个空房子,则将无法读取之后的所有房子。为获得更具体的答案,我可能需要房屋类结构和用于创建输出文件的过程, hasnext在while条件和readline使用hasnext从字符串值``手动''构造一个house对象。

This here: 这里:

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("output.txt"));

is a contradiction in itself. 本身就是一个矛盾。 You see, when you serialize java objects via the standard Java mechanism, you end up with bytes . 您会看到,当通过标准Java机制序列化 Java对象时,最终会得到bytes Binary data. 二进制数据。

Thus: 从而:

  • either your file has a wrong file extension (and is binary, not text) OR: 您的文件扩展名错误(并且是二进制文件,不是文本),或者:
  • whatever you have in that file ... isn't binary data. 该文件中的任何内容……都不是二进制数据。

The exception implies that the second case is more likely. 该例外意味着第二种情况更有可能发生。

In other words: verify what really is in that "output.txt" file. 换句话说:验证该“ output.txt”文件中的真正内容。 Obviously, not the result of serializing Java objects. 显然,这不是序列化Java对象的结果。

(note: of course, the file extension doesn't matter, but it implies that the file really is something different then what you expect it to be) (注意:当然,文件扩展名无关紧要,但这意味着文件确实与您期望的有所不同)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM