从文件中读取对象并将其添加到数组

时间:2019-04-11 13:17:13

标签: java

我正在尝试从文件中读取对象,然后将它们添加到票证的数组列表中。但这不起作用。我可以知道问题出在哪里吗?

public void writeTicketToFile(Ticket ticket) {
    try {
        FileOutputStream fileOut = new FileOutputStream("tickets.txt");
        ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
        objectOut.writeObject(ticket.toString());
        objectOut.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

public void readTicketFromFile(){
    ArrayList<Ticket> tickets = new ArrayList<Ticket>();
    try {
        FileInputStream fi = new FileInputStream(new File("tickets.txt"));
        ObjectInputStream oi = new ObjectInputStream(fi);
        Ticket ticket;
        while (ticket=oi.readObject() != null){
            tickets.add((Ticket)oi.readObject());
        }
        System.out.println(tickets);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

3 个答案:

答案 0 :(得分:1)

您的主要问题之一在于:

while (ticket=oi.readObject() != null){
  tickets.add((Ticket)oi.readObject());
}

比较您尝试将Ticket写入文件的方式来读取文件中的Ticket对象的情况:

objectOut.writeObject(ticket.toString());

如您所见,您正在将Ticket转换为String并将String写入文件。然后,当您尝试阅读时,您正在尝试阅读Ticket。相反,您应该阅读String,然后将String转换为代码中的Ticket

如果Ticket是可序列化的,您可能只能从写入步骤中删除.toString(),但是我从来没有使用过对象流,所以我不能说是100%会起作用。

答案 1 :(得分:0)

只需将Ticket对象添加到ArrayList中,并将列表(而不是每个对象一个接一个地)写入单个对象。然后以readTicketFromFile()方法从文件中读取列表:

 ArrayList<Ticket> ticketsList = (ArrayList<Ticket>)oi.readObject();

答案 2 :(得分:0)

这里有很多问题:

请确保您的票证实现了Serializable接口,用于从文件中写入对象/从文件中读取对象,如以下简单示例所示:

public class Ticket implements Serializable{

private String name;
private LocalDateTime issued;

public Ticket() {
}

public Ticket(String name, LocalDateTime issued) {
    this.name = name;
    this.issued = issued;
}

/**
 * @return the name
 */
public String getName() {
    return name;
}

/**
 * @param name the name to set
 */
public void setName(String name) {
    this.name = name;
}

/**
 * @return the issued
 */
public LocalDateTime getIssued() {
    return issued;
}

/**
 * @param issued the issued to set
 */
public void setIssued(LocalDateTime issued) {
    this.issued = issued;
}

}


现在在将票证写入文件时要注意一次写入一张票证。您可以通过遍历票证列表并一次写入一张票证来实现此目的,例如:

for (int i = 0; i < tickets.size(); i++) {
                    objectOut.writeObject(tickets.get(i));
                }

此外,请确保在阅读后关闭ObjectInputStream,因为它肯定会在末尾抛出EOFException,并看一下在readTicketFromFile方法中的实现。


public class SerializationAndDeserializationOfTicket {

    public static void main(String[] args) {
        List<Ticket> listOfTickets = new ArrayList<>();
        listOfTickets.add(new Ticket("Concert 1", LocalDateTime.now()));
        listOfTickets.add(new Ticket("Concert 2", LocalDateTime.now()));
        listOfTickets.add(new Ticket("Concert 3", LocalDateTime.now()));

        writeTicketToFile(listOfTickets);

        readTicketFromFile();
    }

    public static void writeTicketToFile(List<Ticket> tickets) {

        try {
            FileOutputStream fileOut = new FileOutputStream("tickets.txt");
            ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
            for (int i = 0; i < tickets.size(); i++) {
                objectOut.writeObject(tickets.get(i));
            }
            objectOut.close();
        } catch (IOException e) {
            System.err.println("JVM reported an IO exception. Please, take a look.");
        }
    }

    public static void readTicketFromFile() {
        ArrayList<Ticket> tickets = new ArrayList<>();
        try {
            FileInputStream fi = new FileInputStream(new File("tickets.txt"));
            ObjectInputStream oi = new ObjectInputStream(fi);
            while (true) {
                try {

                    Ticket ticket = (Ticket) oi.readObject();
                    tickets.add(ticket);
                    System.out.println(ticket.getName() + " " + ticket.getIssued());
                } catch (EOFException ex) {
                    oi.close();
                    break;
                }
            }

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("JVM reported an IO/ClassNotFound exception. Please, take a look.");
    }
    }