如何使用Java将字符串中的逗号分隔值存储为CSV [英] how to store comma separated values in a String to CSV using java

查看:78
本文介绍了如何使用Java将字符串中的逗号分隔值存储为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用以下代码将字符串存储到CSV文件中,但是正在生成空CSV.

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

代码

 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());
        }

预期输出:

数据应在CSV文件中这样显示.

The data should show like this in CSV file.

1杯

蜂蜜

2汤匙

油菜籽

我如何获得预期的结果??

How I could get expected results.?

推荐答案

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

这会将数据保留在一行中,并且每个逗号都按照CSV文件的规则将数据带到新的列中.您需要在数据中添加新行,以在每次逗号后将数据保留在新行中.可以通过此操作完成.

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());
    }

这篇关于如何使用Java将字符串中的逗号分隔值存储为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆