0

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

3
  • Try moving your CSVReader and CSVWriter outside the for loop... Commented Mar 9, 2017 at 18:23
  • You should open both files outside the loop. Otherwise, you are re-opening them again and again Commented Mar 9, 2017 at 18:24
  • When I move them outside of the loop it doesn't print out the contents 5 times, nor does the CSV contain the contents 5 times. Commented Mar 9, 2017 at 18:28

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

6 Comments

Nice, that's definitely better but it's printing like this: [a,a,a,a,a, b,b,b,b,b,b, c,c,c,c,c] as opposed to [a, b, c, a, b, c, a ,b ,c, a, b, c a, b, c]
I don't know what your inputs are, but that seems like a logic error on your end
Yes, I know it probably seems a bit weird but that's the format I require it in. I am pulling me hair out over it!
If your file contains a,b,c (each on a new line). Then you must read that entire file into a String[], and then write a for loop to the writer.
Thanks, you have taught me somethings today but the answer below helped me work out the problem on this one. It appears my loops were correct but I just need to add the true to the end. Thank you for your support.
|
1

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.

2 Comments

Wow, I kept the reader and writer where they are in the code and put the true at the end as you suggested and it worked! Thanks very much!
@slowpoke88, yeah that was the only part missing as far as the main problem of overwriting was concerned. However, you should still optimize your code as per the other comments to make your program perform better.
-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();
            }
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.