包含逗号的字符串输入到csv文件 [英] String containing comma inputting in to the csv file

查看:289
本文介绍了包含逗号的字符串输入到csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试输入csv文件。

我的输入如下所示

String string =hi,这是用户;

,但是当我输入到csv文件中时,逗号被作为分隔符,它被写在两个单元格中。 hi在一个单元格中,这是用户在另一个单元格中。

但是我想要整个字符串在一个单元格。

我如何实现这一点。 >
请帮助我。

  FileWriter writer = new FileWriter(D:/Workspace/Sample2.csv) ; 
PrintWriter out = new PrintWriter(writer);

String names =[hasds,jash.jahd,jash];
out.append(names);
out.flush();
}


解决方案

csv 文件和逗号分隔符,并且您的文本恰好有逗号

 双引号 String names =\hi,这是user\; 

注意要将文本包含在双引号内,



更新: - 示例代码段将您的字符串包含在双引号内。

  public static void main(String [] args){

String test =abcd;
System.out.println(test); // prints abcd
test = appendDQ(test);
System.out.println(test); // printsabcd

}

private static String appendDQ(String str){
return\+ str +\ ;
}


I am trying to input in to the csv file.
My input is as shown below
String string="hi,this is user";
but when i am inputing in to the csv file the comma is taken as delimiter and it is written in two cells. "hi" in one cell and "this is user" in another cell.
But i want the whole string to be in one cell.
How can i achieve this.
Please help me.

FileWriter writer = new FileWriter("D:/Workspace/Sample2.csv");
PrintWriter out = new PrintWriter(writer);

String names="[hasds,jash.jahd,jash]";
    out.append(names);
    out.flush();
}

解决方案

Since you're writing a csv file, with comma delimiter, and your text happens to have a comma in it as well, you need to wrap your text within double quotes.

String names = "\"hi,this is user\"";

Note that to wrap your text within double quotes, you need to escape the double quotes as well!

Update:- A sample code snippet to wrap your string within double quotes.

public static void main(String[] args) {

    String test = "abcd";
    System.out.println(test); // prints abcd
    test = appendDQ(test);
    System.out.println(test); // prints "abcd"

}

private static String appendDQ(String str) {
    return "\"" + str + "\"";
}

这篇关于包含逗号的字符串输入到csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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