java-在csv文件中编辑内容

这篇博客讨论了如何在Java中编辑CSV文件的内容。作者遇到一个问题,即虽然程序提示已成功编辑,但实际CSV文件并未更新。问题在于代码没有正确地将编辑后的ArrayList<Animals>写回文件。解决方案建议使用类似的方式覆盖CSV文件中的特定行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我正在尝试找到一种方法来编辑csv文件的内容.

 

主应用

 

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).");

            }
}
}

动物经理

 

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("[,\r\n]+");
            //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();
    }
}

这里的想法是提供您要编辑并写下新信息以替换旧信息的特定动物ID.但是,该代码似乎不起作用-当我运行该程序时,它会提示“已成功编辑”,但csv文件的内容保持不变.

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

最佳答案

从您提供的代码的外观来看,您似乎无法写入ArrayList< Animals>的内容. animalList;归档.为了澄清,请注意

 

 

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.
      }
}

不会覆盖磁盘上CSV文件的副本.而是,整个操作发生在CSV文件的ArrayList表示形式中.它编辑已存储在易失性内存中的动物对象,但不会将它们转换回CSV文件.

通过类似于How to replace a specific line in a file using Java?的解决方案覆盖CSV文件中的特定行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值