简体   繁体   English

OpenCSV CSVWriter在文件末尾添加空白行

[英]OpenCSV CSVWriter adds blank line to end of file

I'm using the following code to remove quotemarks from a pipe-delimited CSV: 我正在使用以下代码从以竖线分隔的CSV中删除引号:

public Path truncateQuoteMarks(Path path) throws Exception {

    String pipeDelimitedFilename = path.toAbsolutePath().toString();

    Path convertedFilename = Paths.get(pipeDelimitedFilename.substring(0, pipeDelimitedFilename.lastIndexOf(".csv")) + "_no_quotes.csv");

    CSVReader reader = new CSVReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(path.toAbsolutePath().toString()))), '|', CSVParser.DEFAULT_QUOTE_CHARACTER);

    reader.skip(1);

    FileWriter fw = new FileWriter(convertedFilename.toAbsolutePath().toString());
    fw.write(System.lineSeparator());
    CSVWriter writer = new CSVWriter(fw, '|', CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.RFC4180_LINE_END);

    String[] currentLine;
    while((currentLine = reader.readNext()) != null) {
        writer.writeNext(currentLine);
    }

    writer.flush();
    writer.close();
    reader.close();

    return convertedFilename;
}

However, it leaves a blank line at the end of the csv (see picture). 但是,它在csv的末尾留有空白行(请参见图片)。 在此处输入图片说明

Upon googling i found that this has been asked at least once both here and in another site. 谷歌搜索后,我发现这在这里和另一个站点都至少被问过一次。 The other site claims that this is the way OpenCSV works and suggested editing the file size, but there has to be other ways. 另一个站点声称这是OpenCSV的工作方式,建议编辑文件大小,但是必须有其他方法。

Is there a way to remove this blank line from the end of the file? 有没有办法从文件末尾删除此空白行? SQL Server BULKINSERT does not like it at all. SQL Server BULKINSERT根本不喜欢它。

According to RFC4180 the final lineending is optional. 根据RFC4180 ,最后的行尾是可选的。 So a writer can or can not write it. 因此,作家可以写也可以不写。 The openCSVWriter has not option to create a final without line ending. openCSVWriter不能选择创建没有行结尾的最终版本。 You can extend the Class and add a setter for the line ending and set it empty before writing the last line or write it manual. 您可以扩展该类并为行尾添加一个setter,并在写最后一行或手动编写之前将其设置为空。

For each of this possibilities you should have a look at the source of the writer . 对于每一个这种可能性,你应该有一个看看源作家

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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