我正在用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);
只需将管道字符作为默认分隔符传递即可。
CSVWriter csvWriter = new CSVWriter(writer,'|');