Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

java - String containing comma inputting in to the csv file

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();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 + """;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...