如何从csv文件中删除特定条目?

时间:2016-01-18 16:24:56

标签: java csv filewriter

我在java中使用程序将地址保存并删除到csv文件中。现在我想从csv文件中删除一个特定的地址,以便为此编写一个函数 喜欢

public String deleteAddress(String firstName,String LastName,String msg) throws IOException{
  Iterator<Address> it = addressBook.iterator();
  n=msg;
        while(it.hasNext()){
            Address newObj = it.next();
            if((newObj.getFirstName().equalsIgnoreCase(firstName) == true) && (newObj.getLastName().equalsIgnoreCase(LastName) == true)){
                File newfile = new File("address.csv");
                BufferedWriter bw = new BufferedWriter(new FileWriter(newfile));
                it.remove();
                n="found and removed";
            }
       }


       for(Address newObj : addressBook){
            AddressBookSave.saveAddressBookToFile(newObj);
      }
       return n;
}
}

但它无法正常工作。有人请帮我解决这个问题。

2 个答案:

答案 0 :(得分:1)

请参阅SO的此链接,Boolean.TRUE == myBoolean vs. Boolean.TRUE.equals(myBoolean)

这里假设lastIndexOf已正确填充数据。 在您的源代码中,您不应该使用addressBook进行检查,因为== true方法已经返回equalsIgnoreCase()true,而不会返回任何其他内容。

将其更改为

false

另外要避免使用if((newObj.getFirstName().equalsIgnoreCase(firstName)) && (newObj.getLastName().equalsIgnoreCase(LastName))) ,最好始终将您已知道的值放在第一个位置,例如

NullPointerException

答案 1 :(得分:0)

执行删除和添加的代码,包括加载和保存文件的逻辑缺失或不完整。看来你想要做的事实上很容易。

我不确切地知道你的要求enter code here是什么,我无法在标记上找到它。但是,这是一个完整的示例类,我在Groovy中编写(非常接近Java - 但更好),它完成了我认为你想要完成的事情。如果这对您有帮助,请将此示例标记为明确答案。

随意运行下面的Groovy类并试一试。

import groovy.transform.Canonical

import javax.swing.*

public class AddressBook {
    List<Address> addressBook = new ArrayList<>();
    String filePath;

    public String deleteAddress(String firstName, String lastName) {
        String result = "Not Found"
        Iterator<Address> iter = addressBook.iterator();
        while(iter.hasNext()){
            Address addy = iter.next();
            if ((addy.getFirstName().equalsIgnoreCase(firstName)) && (addy.getLastName().equalsIgnoreCase(lastName))) {
                iter.remove();
                result = "Address was found and removed..save to update the file.";
            }
        }

        println result;
        return result;
    }

    void addAddress(String firstName, String lastName, String addyString){
        addressBook.add(new Address("firstName":firstName, "lastName":lastName, "address":addyString));
        println "Address added..save to update the file.";
    }

    void saveAddressBookToFile() throws IOException{
        BufferedWriter bw = null;
        println "Saving addresses to file: " + filePath;
        try{
            File file = new File(filePath);
            bw = new BufferedWriter(new FileWriter(file));
            file.createNewFile()
            for(Address addy: addressBook){
                bw.write(addy.toString() + "\n");
            }
            bw.flush();
        }
        finally{
            if(bw){
                bw.close();
            }
        }
    }

    void loadAddressBook(String path) throws IOException{
        addressBook.clear();
        filePath = path;
        BufferedReader br = null;
        try{
            List<String> lines = new BufferedReader(new FileReader(path)).readLines();
            for(String line: lines){
                addressBook.add(new Address(line));
            }
            println path + " loaded successfully."
        }
        catch(FileNotFoundException fnfe){
            println "File " + path + " does not exist, nothing loaded.";
        }
        finally {
            if (br) {
                br.close()
            }
        }
    }

    void printLoadedAddresses(){
        for(Address addy: addressBook){
            println addy.prettyString();
        }
    }

    public static void main(String... args) {
        AddressBook ab = new AddressBook();
        String readln = ' '

        while(readln){
            readln = JOptionPane.showInputDialog('Please input a valid command: load, add, delete, save')

            if (readln) {
                args = readln.split()
                switch (args[0]) {
                    case "load":
                        if (args.length < 2) {
                            println("You did not provide the second argument for the address csv file path.")
                            break;
                        } else {
                            ab.loadAddressBook(args[1])
                        }
                        break;
                    case "add":
                        if(args.length < 4){
                            println("Please provide the firstName, lastName, and address parameters when adding.")
                        }
                        else {
                            ab.addAddress(args[1], args[2], args[3..-1].join(" "));
                        }
                        break;
                    case "delete":
                        if(args.length < 3){
                            println("Please provide the firstName, lastName, and address parameters when deleting.")
                        }
                        else {
                            ab.deleteAddress(args[1], args[2]);
                        }
                        break;
                    case "save":
                        if (ab.filePath) {
                            ab.saveAddressBookToFile();
                        } else {
                            println("You must first call load with a file path for the csv file (even it it doesn't exist yet.")
                        }
                        break;
                    case "print":
                        ab.printLoadedAddresses();
                        break;
                    case "exit":
                        System.exit(0)
                    default:
                        println "Unrecognized command: " + args[0]
                }
            }
        }
    }
}

@Canonical
class Address {
    String firstName;
    String lastName;
    String address;

    public Address(){
        super
    }

    public Address(String csvString){
        List<String> tokens = csvString.split(",");
        firstName = tokens[0];
        lastName = tokens[1];
        address = tokens[2]
    }

    @Override
    public String toString(){
        return firstName + "," + lastName + "," + address;
    }

    public String prettyString(){
        return firstName + " " + lastName + " - " + address;
    }
}