pramod patel
pramod patel

Reputation: 135

Write to the CSV File

I am combining the two csv file with different headers. I am getting problem with writing the values to new csv. Anyone help on this.

The values from csv file are merged and printing in console. i need to write those values to new csv file.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class MainCSV {

    public static void main(String[] args){
        MainCSV obj = new MainCSV();
        obj.run();
    }
     public void run() {

            String csvFile = "E:/CSV/6d54979e-60da-4c73-b6e5-b2138a7450ca.csv";
            String csvFile2 = "E:/CSV/9b5659f2-38e8-4bbd-bd7c-74ad683d5c59.csv";

            BufferedReader br = null;
            BufferedReader br2 = null;

            String line = "";
            String line2 = "";

            try {

                br = new BufferedReader(new FileReader(csvFile));
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
                br2 = new BufferedReader(new FileReader(csvFile2));
                System.out.println("--------------------------------------------------------");
                while ((line2 = br2.readLine()) != null) {

                    System.out.println(line2);
                    StringBuffer strbuf;

                    strbuf = new StringBuffer(line2);                                       
                }


            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            System.out.println("Done");
          }
}

Upvotes: 1

Views: 112

Answers (2)

mountiealpha
mountiealpha

Reputation: 31

You'll need to use something to output to a file instead of the console (System.out.println prints to the console). Try, for example: http://www.java2s.com/Tutorial/Java/0180__File/WritelinesoftexttofileusingaPrintWriter.htm Also, as ztrn mentioned above, you need to make sure your data columns line up between the two files. You may need to discard the first line of the second CSV if it contains header information. Lastly, make sure you don't print the line of hyphens to the file, or "Done.", else you'll have garbage data.

Upvotes: 2

dehasi
dehasi

Reputation: 2773

If you have different headers it means that you have different columns (and amount of columns). So you have to resolve how to combine two different tables. In your source I can't see what do you want and what wrong. Add stacktrace or smth else, please.

Upvotes: 2

Related Questions