我正在用Java写一个csv文件,我想用'|'写一个csv文件。作为分隔符。我该怎么办我的代码。
这是我的Java代码:

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();
    }
}

最佳答案

使用此代码段实例化CSVWriter

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

10-08 02:00