Search code examples
javacsvopencsv

Java read CSV file ,contents not write in new CSV file


package com;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import com.opencsv.CSVWriter;
import com.opencsv.CSVReader;

public class Sample2 {
    public static void main(String args[]) throws IOException
    {
        CSVReader csvReader = null;  
        String[] employeeDetails ;        
        CSVWriter  csvWriter = new CSVWriter(new FileWriter("D:\\sample\\myfile.csv",true));
        csvReader = new CSVReader(new FileReader("D:\\sample\\source.csv"));          
        try
        {        

            employeeDetails = csvReader.readNext();               
            while ((employeeDetails = csvReader.readNext()) != null ) {               

                    System.out.println(Arrays.toString(employeeDetails));                   
                    csvWriter.writeNext(employeeDetails);
                }               

        }catch(Exception ee)
            {
                ee.printStackTrace();
            }
        }
}

I have my above java code It read data from source.csv file and also display in the console . It created myfile.csv ,but same contents it didn't write in the csv file Anyone have any idea on this


Solution

  • The issue is that you don't close your output resources, try this code:

    public static void main(String args[]) throws IOException {
    String[] employeeDetails;
    
    try (CSVWriter csvWriter = new CSVWriter(new FileWriter("D:\\sample\\myfile.csv", true));
        CSVReader csvReader = new CSVReader(new FileReader("D:\\sample\\source.csv"));
        ) {
    
      while ((employeeDetails = csvReader.readNext()) != null) {
    
        System.out.println(Arrays.toString(employeeDetails));
        csvWriter.writeNext(employeeDetails);
      }
    }
    catch (Exception ee) {
      ee.printStackTrace(); //perhaps you should also log the error?
    }
    }
    

    Also take a look at this question Is closing the resources always important?