slowpoke88
slowpoke88

Reputation: 3

How to loop and write the same content to a CSV file in Java

I have a CSV file which I read from and store its contents as a String Array.
I want to then write that input back to a separate CSV file, but I want to loop through and write the contents back 5 times to that CSV file.

The following code works when it prints out the code, but I assume it is overwriting the file each time when it writes to the CSV file, because it only contains 1 iteration of the loop in the CSV file?

@SuppressWarnings("resource")
public static void main(String[] args) throws Exception {

    String[] nextLine = null;

    for (int i = 0; i<=5; i++){
        CSVReader reader = new CSVReader(new FileReader("D:\\input.csv"), ',' , '"' , 1);
        CSVWriter writer = new CSVWriter(new FileWriter("D:\\output.csv"));
        while ((nextLine = reader.readNext()) != null) {
            //Write the record to Result file
            writer.writeNext(nextLine);                 
            System.out.println(Arrays.toString(nextLine));

        }
        i++;
        writer.flush();
        writer.close();
    }

Edit: the format I require is [a,b,c,a,b,c,a,b,c...] as opposed to [a,a,a,b,b,b,c,c,c...] so let's say my input file is [item1 dog cat item2 dog cat item3 dog cat] then I would expect it to print like 5 times in sequential order and not like [item 1, item 1, item 1, item 1, item 1, dog, dog...]

Upvotes: 0

Views: 4200

Answers (3)

T. J.
T. J.

Reputation: 1

I have edited the post submitted and moved the for loop outside the while loop and put the try inside the for loop. This should produce the desired results you are looking for

public static void main(String[] args) throws Exception {

    String[] nextLine = null;

    try (


    ) {
        for (int i = 0; i < 5; i++){
             try (
                  CSVReader reader = new CSVReader(new FileReader("D:\\input.csv"), ',' , '"' , 1);
                  CSVWriter writer = new CSVWriter(new FileWriter("D:\\output.csv", true));
             ){
               while ((nextLine = reader.readNext()) != null) {
            // Write 5 records to Result file

                writer.writeNext(nextLine);                 
                System.out.println(Arrays.toString(nextLine));
                  }
                writer.flush();
            }
        }
    }
}

Upvotes: -1

VHS
VHS

Reputation: 10194

Replace

CSVWriter writer = new CSVWriter(new FileWriter("D:\\output.csv"));

with

//Open for append
CSVWriter writer = new CSVWriter(new FileWriter("D:\\output.csv", true));

Also, as the other comments mention, you might want to refactor your code to open/close files only once.

Upvotes: 1

OneCricketeer
OneCricketeer

Reputation: 192043

1) You've got your loops backwards. You want to read a line, then write 5 times.

2) Your for loop actually runs 6 times with i <= 5.

3) You don't need to i++ within the for loop again


Try the following

public static void main(String[] args) throws Exception {

    String[] nextLine = null;

    try (
        CSVReader reader = new CSVReader(new FileReader("D:\\input.csv"), ',' , '"' , 1);
        CSVWriter writer = new CSVWriter(new FileWriter("D:\\output.csv"))
    ) {
        while ((nextLine = reader.readNext()) != null) {
            // Write 5 records to Result file
            for (int i = 0; i < 5; i++){
                writer.writeNext(nextLine);                 
                System.out.println(Arrays.toString(nextLine));

            }
            writer.flush();
        }
    }

(try with resources will close the files itself)

Upvotes: 2

Related Questions