我想创建一个csv文件,其中分隔符是逗号seperated.While csv是读取它使s5字符串在逗号分隔。希望将s5字符串保留在单列中。
String s1="quick";
String s2="brown";
String s3="fox";
String s4="jump";
String s5="over,the,lazy,dog";
String csvRecord = String.format("%s,%s,%s,%s,%s", s1,s2,s3,s4,s5);
有人能帮我吗,因为我对弦还不熟悉。
发布于 2018-08-14 17:07:45
我认为您需要将它们添加到一个双字符串中。
试试这个:
String s5="\"over,the,lazy,dog\"";
发布于 2018-08-14 17:36:49
要在数据中包含分隔符,必须在生成的csv中使用双引号将字段括起来:
quick,brown,fox,jump,"over,the,lazy,dog"
如果某些字段中有双引号,则必须对其进行转义:
123,"24"" monitor, Samsung",456 // Windows style
123,"24\" monitor",456 // Linux style
您不必引用所有字段,只需包含分隔符或双引号(或换行符)的字段即可。
有关csv通用格式的更多详细信息,请参阅RFC4180。
发布于 2018-08-14 17:46:50
就像前面提到的其他答案一样,你实际上必须考虑许多特殊情况,最典型的两种特殊情况是:逗号和双引号。
在随信附上的CSV wiki中,明确规定了格式为:
Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00
要处理这两种情况,您可以尝试如下所示:
public class CsvAddComma {
public static void main(String... args) {
List<String> list = new ArrayList<>();
list.add("quick");
list.add("over,the,lazy,dog");
list.add("Venture \"Extended Edition, Very Large\"");
list.stream()
.map(s -> convertToCsvFormat(s))
.forEach(System.out::println);
}
private static String convertToCsvFormat(String input) {
if (input.contains("\"")) {
input = input.replaceAll("\"", "\"\"");
}
if (input.contains(",")) {
input = String.format("\"%s\"", input);
}
return input;
}
}
和输出:
quick
"over,the,lazy,dog"
"Venture ""Extended Edition, Very Large"""
对于其他特殊情况,您需要根据您当前的情况进行处理。也许它们可以被忽略,也许不可以。
https://stackoverflow.com/questions/51837647
复制相似问题