String containing comma inputting in to the csv file

后端 未结 2 1413
轮回少年
轮回少年 2020-12-19 04:17

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 tak

相关标签:
2条回答
  • 2020-12-19 05:02

    You have to ensure the data is properly escaped. Commas and double-quotes require special handling. I would highly recommend using a library to take care of all details of properly escaping csv data for you. Take a look at opencsv.

    0 讨论(0)
  • 2020-12-19 05:06

    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 + "\"";
    }
    
    0 讨论(0)
提交回复
热议问题