我正在用Java编写一个csv文件,我想用'|'写一个csv文件。作为分隔符。我该怎么办?
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();
}
}
答案 0 :(得分:2)
使用此代码段实例化CSVWriter
。
CSVWriter csvWriter = new CSVWriter(writer,
'|',
CSVWriter.NO_QUOTE_CHARACTER,
CSVWriter.DEFAULT_ESCAPE_CHARACTER,
CSVWriter.DEFAULT_LINE_END);
答案 1 :(得分:1)
只需将管道字符作为默认分隔符即可。
CSVWriter csvWriter = new CSVWriter(writer,'|');