【问题标题】:How to read an ArrayList from a File into another ArrayList?如何将一个 ArrayList 从一个文件读入另一个 ArrayList?
【发布时间】:2014-02-05 19:58:52
【问题描述】:

我试图将一个数组列表从一个文件读取到另一个数组列表中,但我不断收到错误消息。该文件名为 eventos.dat,arraylist 来自 Evento 类型。我想用文件中数组中的对象创建一个新的ArrayList<Evento>。这是我正在使用的方法:

public class ListaEventos implements Serializable{
    private  ArrayList<Evento> eventos = new ArrayList();

    public String adicionarEvento(Evento novo){
         for (Evento evento : eventos) {
             if(novo.equals(evento)){
                return "Evento já existe";
            }     
        }
        eventos.add(novo);
        return "ADICIONEI";

    }


    public  ArrayList<Evento> getEventos() {
        return eventos;
    }

    public Evento procuraEvento(String tituloEvento){
        for (Evento evento : eventos){
            if(tituloEvento.equals(evento.getTitulo())){
                return evento;
            }
        }
        return null;
    }

    public String editaEvento(Evento antigo, Evento novo){
        for (int i=0;i<eventos.size();i++){
            if(antigo.equals(eventos.get(i))){
                eventos.get(i).setTitulo(novo.getTitulo());
                eventos.get(i).setData(novo.getData());
                eventos.get(i).setDescricao(novo.getDescricao());
                eventos.get(i).setLocal(novo.getLocal());
                eventos.get(i).setPrivado(novo.getPrivado());
                return "Editei evento";
            }
        }
        return "Evento não existe";
    }

    public String removeEvento(String removeTitulo){
        Evento aux= procuraEvento(removeTitulo);

        if(aux != null){
            eventos.remove(aux);
            return "Evento removido!";
        }
        return "Evento não existe";
    }



    public void gravaFicheiro(){
        try{
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Eventos.dat"));
            out.writeObject(eventos);
            out.close();
        }
        catch(IOException ex){
            System.out.println("Não conseguiu gravar");
        }
    }

    public ArrayList<Evento> carregaEventos() throws ClassNotFoundException{

       try{

            ObjectInputStream in = new ObjectInputStream(new FileInputStream ("Eventos.dat"));
            eventos=(ArrayList<Evento>) in.readObject();
            in.close();
            return eventos;

        }catch(IOException ex){
            System.out.println("Ficheiro não existe");
            return null;
        }
    }
}

这是Evento 类:

public class Evento implements Serializable {

    private String titulo = "Nao preenchido";
    private String data = "Nao preenchido";
    private String local = "Nao preenchido";
    private String descricao = "Nao preenchido";
    private String privado = "Nao preenchido";
    private ArrayList<Contacto> convidados = new ArrayList();

   public Evento() {

    }

    public Evento(String titulo, String data, String local, String descricao, String privado) {
        this.titulo = titulo;
        this.data = data;
        this.local = local;
        this.descricao = descricao;
        this.privado = privado;
    }

    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }

    public void setData(String data) {
        this.data = data;
    }

    public void setLocal(String local) {
        this.local = local;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public void setPrivado(String privado) {
        this.privado = privado;
    }


    public String getTitulo() {
        return titulo;
    }

    public String getData() {
        return data;
    }

    public String getLocal() {
        return local;
    }

    public String getDescricao() {
        return descricao;
    }

    public String getPrivado() {
        return privado;
    }

    public ArrayList<Contacto> getConvidados() {
        return convidados;
    }

    public void setConvidados(ArrayList<Contacto> convidados) {
        this.convidados = convidados;
    }

    public String adicionaConvidado(String nomeConvidado){
        Contacto novo = new Contacto();
        for (Contacto contacto : this.convidados) {
             if(nomeConvidado.equals(contacto.getNome())){
                return "Contacto já foi convidado";
            }
         }
        novo.setNome(nomeConvidado);
        novo.setEmail("");
        novo.setTelefone("");
        convidados.add(novo);
        return "ADICIONEI CONVIDADO";

    }

    public Evento(String titulo, String local) {
        this.titulo = titulo;
        this.local = local;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Evento other = (Evento) obj;
        if (!Objects.equals(this.titulo, other.titulo)) {
            return false;
        }
        if (!Objects.equals(this.data, other.data)) {
            return false;
        }
        if (!Objects.equals(this.local, other.local)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "Evento{" + "titulo=" + titulo + ", data=" + data + ", local=" + local + ", descricao=" + descricao + ", privado=" + privado + ", convidados=" + convidados + '}';
    }

    @Override
    public int hashCode() {
        int hash = 7;
        return hash;
    }

将 CarregaEvento 方法更改为:

public ArrayList<Evento> carregaEventos() throws ClassNotFoundException {

    try{

        ObjectInputStream in = new ObjectInputStream(new FileInputStream ("Eventos.dat"));
        eventos=(ArrayList<Evento>) in.readObject();
        in.close();
        return eventos;

    }catch(IOException ex){
        System.out.println("Ficheiro não existe");
        return null;
    }           

}

没有错误但仍然不起作用。

【问题讨论】:

  • 请发布你的Evento类(至少我们需要知道构造函数,以及eventos.dat的格式)。
  • 您遇到错误了吗?
  • 有什么问题?
  • @mattforsy 很确定 list.add(s.next()) 应该在编译时失败
  • @AndréViegas why 非常简单。 list 是一个ArrayList&lt;Evento&gt;,这意味着list.add(..) 需要一个Evento 类型的参数。 Scanner#next 返回 String。这里有类型不匹配。至于修复它,我不知道java对象序列化是如何工作的,但是tutorialspoint.com/java/java_serialization.htm可能会有所帮助

标签: java file arraylist


【解决方案1】:
eventos=(ArrayList<Evento>) in.readObject();

这不会创建ArrayList&lt;Evento&gt; 的新类型。

尽管您可以使用读取文本文件时提供的字符串创建 Evento 的新实例。您可以使用String 类中的split(String par1) 方法创建Evento 的新实例并将其添加到arraylist。

有关拆分的更多信息,请参阅JavaDocs

【讨论】:

    猜你喜欢
    • 2022-06-12
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 2018-07-21
    • 2014-03-18
    • 2013-12-30
    相关资源
    最近更新 更多