【问题标题】:Delete row in a CSV file and export file in JAVA在 CSV 文件中删除行并在 JAVA 中导出文件
【发布时间】:2014-06-16 01:59:31
【问题描述】:

我有一个程序,我在其中读取 CSV 文件并导出文本文件类型。 CSV 属性是姓名、出生日期、电子邮件和地址。

我需要一个 BufferedReader,用户可以插入其中一条记录的电子邮件并删除 CSV 中的整行(删除姓名、出生日期和电子邮件地址)并重新导出文本文件类型。

我对 Java 了解不多,无法帮助我找到解决方案。

我分享代码,

感谢您的帮助,

谢谢!

public class Personas {
private String nombre;
private String fechaNacimiento;
private String email;
private String direccion;

public Personas(String nombre, String fechaNacimiento, String email,
        String direccion) {
    super();
    this.nombre = nombre;
    this.fechaNacimiento = fechaNacimiento;
    this.email = email;
    this.direccion = direccion;
}

public String getNombre() {
    return nombre;
}

public void setNombre(String nombre) {
    this.nombre = nombre;
}

public String getFechaNacimiento() {
    return fechaNacimiento;
}

public void setFechaNacimiento(String fechaNacimiento) {
    this.fechaNacimiento = fechaNacimiento;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getDireccion() {
    return direccion;
}

public void setDireccion(String direccion) {
    this.direccion = direccion;
}


}

这里是主类

import java.io.*;

public class Principal {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Personas[] miLista = new Personas[100];
    int i = 0;
    String texto = "";
    FileReader lector;
    try {
        lector = new FileReader("C:\\Users\\CD\\Downloads\\dummydata.csv");
        BufferedReader contenido=new BufferedReader(lector);
        try {
            while((texto=contenido.readLine())!=null){
                String[] valores = texto.split(",");
                Personas persona = new Personas(valores[0], valores[1], valores[2], valores[3]);
                    miLista[i]=persona;
                    i++;

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println("hay mas de 100 registros en el archivo");                       
            System.out.println("solo se cargaran los primeros 100");                        
        }catch(Exception e){
            System.out.println("error desconocido contacte con el desarrollador...");   
            System.out.println(e.getMessage()); 
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
        System.out.print("El archivo no se encuentra...");
    }catch(Exception e){
        System.out.println("error desconocido contacte con el desarrollador...");   
        System.out.println(e.getMessage()); 

    }

    for (Personas persona : miLista) {
        System.out.print(persona.getNombre());
        System.out.print(persona.getDireccion());
        System.out.print(persona.getFechaNacimiento());
        System.out.println(persona.getEmail());
    }

    File miArchivo = new File("miNuevoArchivo.txt");
    try{
        FileWriter fw = new FileWriter(miArchivo);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter wr = new PrintWriter(bw);  
            for (Personas persona : miLista) {
                wr.write(persona.getNombre()+"\t");
                wr.append(persona.getFechaNacimiento()+"\t");
                wr.append(persona.getDireccion()+"\t");
                wr.println(persona.getEmail());
            }
        wr.close();
        bw.close();
    }catch(IOException e){
        System.out.println(e.getMessage());
    }
}

}

【问题讨论】:

    标签: java csv bufferedreader filereader filewriter


    【解决方案1】:

    我希望它有所帮助......但不确定这是你想要做的。 尽量不要混合使用不同的语言,请参阅 try-with-resource,使用 List (ArrayList) 而不是 Arrays,创建简单的函数并阅读一些关于迭代器的文档。

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Iterator;
    import java.util.List;
    
    public class Principal {
    
        private static final String IN = "C:\\Users\\CD\\Downloads\\dummydata.csv";
        private static final String OUT = "C:\\Users\\CD\\Downloads\\result.txt";
    
        public static List<Personas> readFile(final String file) throws Exception {
            final List<Personas> result = new ArrayList<Personas>();
            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                String texto = "";
                while ((texto = reader.readLine()) != null) {
                    final String[] valores = texto.split(",");
                    final Personas persona = new Personas(valores[0], valores[1], valores[2], valores[3]);
                    result.add(persona);
                }
            }
            return result;
        }
    
        public static void write(final String file, final List<Personas> personas) throws Exception {
            new File(file);
            try (PrintWriter wr = new PrintWriter(new File(file))) {
                for (final Personas persona : personas) {
                    wr.write(persona.getNombre() + "\t");
                    wr.append(persona.getFechaNacimiento() + "\t");
                    wr.append(persona.getDireccion() + "\t");
                    wr.println(persona.getEmail());
                }
            }
        }
    
        public static void main(final String[] args) throws Exception {
            final List<String> emailsToRemove = Arrays.asList("email1@lol.com", "email2@lol.com");
    
            final List<Personas> personas = readFile(IN);
    
            //Remove some personnas
            for (Iterator<Personas> it = personas.iterator(); it.hasNext(); /**RIEN**/) {
                Personas act = it.next();
                if(emailsToRemove.contains(act.getEmail())){
                    it.remove();
                }
            }
    
            write(OUT, personas);
        }
    }
    

    【讨论】:

    • 你好,法维兰!谢谢您的帮助! :D 为什么当我在 Eclipse 中运行程序时,程序不让我输入文本并显示程序结束?我无法测试它是否有效:(
    • 当你运行程序时让你插入邮件?
    • 试试这个:String email = JOptionPane.showInputDialog("Enter email"); 不过剩下的,你得自己干活,该睡觉了
    猜你喜欢
    • 1970-01-01
    • 2020-09-11
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 2021-02-16
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多