Search code examples
javaarraysfileexport-to-csv

how to store comma separated values in a String to CSV using java


I want to store the string into CSV file using the following code but empty CSV is being generated.

Code

 try {
            PrintWriter writer = new PrintWriter(new File("test.csv"));
            StringBuilder sb = new StringBuilder();
            String str ="1 cup, honey, 2 tablespoons ,canola" ;
            sb.append(str);
            writer.write(String.valueOf(sb));

        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        }

Expected Output :

The data should show like this in CSV file.

1 cup

honey

2 tablespoons

canola

How I could get expected results.?


Solution

  •         String str ="1 cup, honey, 2 tablespoons ,canola" ;
    

    This keeps the data in a single line and every comma takes the data to new column as per the rules of CSV file. You need to append a new line in your data to keep your data to new line after every comma. This can be done through this.

     try (PrintWriter writer = new PrintWriter(new File("test.csv"))) {
    
            StringBuilder sb = new StringBuilder();
            String str = "1 cup, honey, 2 tablespoons ,canola";
            String []splitted_str=str.split(",");
            for (String string : splitted_str) {
                sb.append(string).append("\n"); //this will add a new line after every value separated by comma.
            }
            writer.write(sb.toString());
    
            System.out.println("done!");
    
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        }