简体   繁体   中英

How to add delimiter while writing .csv file using openCSV

I'm writing a csv file in java and i want to write csv file with '|' as delimiter. How can i do in my code.

This is my Java code:

public void createCsv(User user) {

    try( FileWriter writer = new FileWriter(CSV_FILE_NAME,true);
            CSVWriter csvWriter = new CSVWriter(writer,
                    CSVWriter.DEFAULT_SEPARATOR,
                    CSVWriter.NO_QUOTE_CHARACTER,
                    CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                    CSVWriter.DEFAULT_LINE_END);

            CSVReader reader = new CSVReader(new FileReader(CSV_FILE_NAME));){

        if(reader.readNext() !=null) {
            csvWriter.writeNext(new String[]{user.getFirstName(), user.getLastName()});             
        }else {
            String[] headerRecord = {"First Name", "Last Name"};
            csvWriter.writeNext(headerRecord);

            csvWriter.writeNext(new String[]{user.getFirstName(), user.getLastName()});             
        }



    } catch (IOException e) {

        e.printStackTrace();
    }
}

Use this snippet for instantiating CSVWriter .

CSVWriter csvWriter = new CSVWriter(writer,
                                    '|',
                                    CSVWriter.NO_QUOTE_CHARACTER,
                                    CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                                    CSVWriter.DEFAULT_LINE_END);

只需将管道字符作为默认分隔符传递即可。

CSVWriter csvWriter = new CSVWriter(writer,'|');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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