Editing content in csv file

问题: I'm trying to find a way to edit the content of a csv file. Main App package project; public class Test { public static void main(String[] ages) { //Loa...

问题:

I'm trying to find a way to edit the content of a csv file.

Main App

package project;


public class Test {

    public static void main(String[] ages) {

        //Load file 
        AnimalManager aMgr = new AnimalManager();
        aMgr.loadFromFile("AnimalDetails.txt");

//        try {
//        Animals anim = aMgr.getAnimalById("48331827032019");
//        aMgr.deleteAnimal(anim);
//        } catch (IllegalArgumentException exc) {
//          System.out.println(exc);
//      }

        System.out.println("Edit Animal:");

        boolean edited = aMgr.editAnimal("48331827032019",5,"German","200","Huskies","Huskies","n","n",1000.0,"John"); //By ID
            if (edited) {
                System.out.println("Animal has been edited successfully.");
            } else {
                System.out.println("Animal not found (test failed).");

            }
}
}

Animal Manager

package project;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;




public class AnimalManager {

    private final ArrayList<Animals> animalList;

    public AnimalManager() {
        this.animalList = new ArrayList<>();
    }

    public boolean addAnimal(Animals a) {
        if (a == null)
            throw new IllegalArgumentException("Animal argument is null");

        if(animalList.contains(a))
            return false;
        animalList.add(a);
        return true;
    }

    public void deleteAnimal (Animals a) {
        if (a == null)
            throw new IllegalArgumentException("Animal argument is null");

        animalList.remove(a);
    }

    public Animals getAnimalById(String ID) {
        for (Animals a : this.animalList) {
            if (a.getID().equals(ID))
                return a; 
        }
        return null;
    }

    public boolean editAnimal(String ID, int age, 
            String breed, String breedPurity, String motherBreed, String fatherBreed, String medicalHistory, String identification, double price, String owner) {
        // test for null and for duplicate
        if (ID == null || age == 0 || breed == null || breedPurity == null || motherBreed == null|| fatherBreed == null || medicalHistory == null|| price == 0 || owner == null)
            throw new IllegalArgumentException("One or more arguments are null");

        // Search for the animal.
        for (Animals p: animalList) {
            if (p.getID().equals(ID)) {
                p.setAge(age);
                p.setBreed(breed);
                p.setMother(motherBreed);
                p.setFather(fatherBreed);
                p.setMedical(medicalHistory);
                p.setIdenti(identification);
                p.setPrice(price);
                p.setOwner(owner);
                return true; // Animal has been edited successfully.
            }
        }
        return false; // Means animal with the supplied id is not found.
    }


    //Load from file
    public void loadFromFile(String filename) {
        try {
            Scanner sc = new Scanner(new File(filename));

            sc.useDelimiter("[,rn]+");
            //animal details: id,age,breed,purity of breed,mother breed,father breed,medical history, identification, price, owner

            while(sc.hasNext()) {
                String ID = sc.next();
                int age = sc.nextInt();
                String breed = sc.next();
                String breedPurity = sc.next();
                String motherBreed = sc.next();
                String fatherBreed = sc.next();
                String medicalHistory = sc.next();
                String identification = sc.next();
                double price = sc.nextDouble();
                String owner = sc.next();

                animalList.add(new Animals(ID, age, breed, breedPurity, motherBreed, fatherBreed, medicalHistory, identification, price, owner ));

            }
            sc.close();

        }catch (IOException e) {
            System.out.println("Exception thrown. " + e);
    }


}

    public String toString() {
        // use String if more comfortable with it - StringBuilding faster for concat
        // than (immutable) String
        StringBuilder strBuilder = new StringBuilder();
        for (Animals p : this.animalList) {
            strBuilder.append(p.toString()).append("n");
        }

        return strBuilder.toString();
    }
}

The idea here is to provide the specific animal ID which you want to edit and write down the new information to replace the old one. However, the code doesn't seem to work - when I run the program it prompts out "edited successfully", but the content of the csv file stays the same.

CSV

0,2,AmercianShorthair,100,AmercianShorthair,AmercianShorthair,y,y,900.0,Ann
3,4,GermanShepherd,100,GermanShepherd,GermanShepherd,no,yes,600.0,Dave
6,3,Poodle,100,Poodle,Poodle,yes,no,300.0,Dianna
456,4,Azawakh,50,Unknown,Azawakh,no,no,300.0,April
25041019042018,1,Vizsla,50,Vizsla,TreeingTennesseeBrindle,no,yes,500.0,Lex
3271,1,Beagle,50,Beagle,Unknown,no,no,200.0,Blanton
48331827032019,33,sheperd,50,50,50,no,yes,300.0,Mike

回答1:

From the looks of the code you provided, it appear that you have failed to write the contents of the ArrayList<Animals> animalList; to file. To clarify, please note that

for (Animals p: animalList) {
    if (p.getID().equals(ID)) {
          p.setAge(age);
          p.setBreed(breed);
          p.setMother(motherBreed);
          p.setFather(fatherBreed);
          p.setMedical(medicalHistory);
          p.setIdenti(identification);
          p.setPrice(price);
          p.setOwner(owner);
          return true; // Animal has been edited successfully.
      }
}

does not overwrite the copy of your CSV file on the disk. Instead, this entire operation occurs in the ArrayList representation of your CSV file. It edits the Animal objects that have been stored in volatile memory, but does not translate them back to the CSV file.

Overwrite specific lines in your CSV file through a solution similar to How to replace a specific line in a file using Java?

  • 发表于 2019-03-30 01:01
  • 阅读 ( 184 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除