Skip to content
Advertisement

Add data to specific record in CSV file

I have a record in a CSV file and i am trying to add some extra info (a name) to the same specific record with the following code but it does not work. There is no error shown but the info i am trying to add just does not appear. What am i missing ?

public class AddName {
public static void main(String[] args) {

    String filepath="Zoo.csv";
    String editTerm="Fish";
    String addedName="Ron";

    addToRecord(filepath,editTerm,addedName);

}
public static void addToRecord(String filepath,String editTerm,String addedName){

    String animal= "";

    try{
        FileWriter fw=new FileWriter(filepath,true);
        BufferedWriter bw=new BufferedWriter(fw);
        PrintWriter pw=new PrintWriter(bw);
            if (animal.equals(editTerm)){
                pw.println(editTerm+","+addedName);
                pw.flush();
                pw.close();
            }
        System.out.println("Your Record was saved");
    }
    catch(Exception e){
        System.out.println("Your Record was not saved");
        e.printStackTrace();
    }
}

Advertisement

Answer

Here the requirement is to add an extra column if the animal name matches. It’s equivalent to changing a particular line in a file. Here’s a simple approach to achieve the same, (Without using any extra libraries),

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class EditLineInFile {

    public static void main(String[] args) {

        String animal = "Fish";

        Path path = Paths.get("C:\Zoo.csv");
        try {
            List<String> allLines = Files.readAllLines(path);
            int counter = 0;
            for (String line : allLines) {
                if (line.equals(animal)) {
                    line += ",Ron";
                    allLines.set(counter, line);
                }
                counter++;
            }
            Files.write(path, allLines);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
Advertisement