简体   繁体   English

转换列表<list<string> &gt; 至 csv </list<string>

[英]Convert List<List<String>> to csv

List<String> a=new ArrayList<>();
a.add("Ross");
a.add("Rachel")'
List<String> b=new ArrayList<>();
b.add("Chandler");
b.add("Monica")'
List<String> c=new ArrayList<>();
c.add("Joey");
c.add("Phoebe");
List<List<String>> x=new ArrayList<>();
x.add(a);
x.add(b);
x.add(c);

I want to convert the list of list of strings x to csv?我想将字符串列表列表 x 转换为 csv? How to achieve that?如何做到这一点?

The csv should look like- csv 应该看起来像 -

Ross Rachel罗斯·雷切尔

Chandler Monica钱德勒莫妮卡

Joey Phoebe乔伊菲比

A simple csv writer could look like this:一个简单的 csv 编写器可能如下所示:

Writer out = System.out; // this could be a FileWriter, StringWriter, etc.
for (List<String> line : x) {
    int n = 0;
    for (String field : line) {
        if (n++ > 0) {
            out.write(",");  // field separator
        }
        out.write(field);
    }
    out.write("\n"); // record separator
}

Not that if any of your strings contain a comma, that field should be wrapped with double-quotes, eg "A,C" .并不是说如果您的任何字符串包含逗号,则该字段应该用双引号括起来,例如"A,C" The code above does not do that.上面的代码没有这样做。 Fields that contain newlines or double-quotes should also be escaped.包含换行符或双引号的字段也应该转义。 There's no single specification that defines how these escapes work in all cases, so that sometimes turns into trial and error to see what works in the app your file will be imported into.没有单一的规范来定义这些转义在所有情况下如何工作,因此有时会变成反复试验,以查看您的文件将导入到的应用程序中的工作原理。

Sometimes csv files have comma separated field names in the first first line, sometimes not.有时 csv 文件在第一行有逗号分隔的字段名称,有时没有。

Variants of csv use different characters for field separator, eg "\t" or "|" csv 的变体使用不同的字符作为字段分隔符,例如“\t”或“|”

There are libraries such as opencsv that handle these complexities, so for non-trivial cases it can be useful to use those instead of re-inventing basic functionality like this.有诸如 opencsv 之类的库可以处理这些复杂性,因此对于非平凡的情况,使用这些库而不是像这样重新发明基本功能会很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM