2

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

0

3 Answers 3

5
        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());
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Actually, with this code you don't need to close() the writer (or even flush() it, for that matter). - the try-with-resources you use does that for you.
@daniu thanks for sharing that. I'll update my answer
2

You need to flush the writer content . add writer.flush() after writer.write()

You can refer to this answer

and also remember to close the writer stream for resource optimization.

Comments

1

Because I like short code:

String str = "1 cup, honey, 2 tablespoons ,canola";
try (PrintWriter writer = new PrintWriter(new File("test.csv"))) {
    Arrays.stream(str.split(",")).map(String::trim).forEach(writer::println);
} catch (FileNotFoundException e) {
    System.out.println(e.getMessage());
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.