2

I want to insert a blank line in csv using java. I have written following code:

CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n").withEscape('\\');
FileWriter fileWriter = new FileWriter(csvFile);

CSVPrinter csvFilePrinter = new CSVPrinter(fileWriter,csvFileFormat);

csvFilePrinter.printRecord("data1");
csvFilePrinter.printRecord("\n");
csvFilePrinter.printRecord("data2");

When I open this generated CSV in notepad++, I am getting 2 blank lines:

 data1
 " 
 "
 data2

How can I get a single blank line?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Radhika Kulkarni
  • 298
  • 1
  • 4
  • 19

4 Answers4

3

printRecord prints a record separator after the data, in this case a newline.

Then you print a newline which is printed as a string containing another newline, which gives you those two double quotes on separate lines.

Just remove the one that prints a newline or, if you really want that empty line, use csvFilePrinter.println() which will output the record separator (in your case, "\n").

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
2

Try csvFilePrinter.printRecord(""); csvFilePrinter.println(); printRecord will escape the line automatically. You do not need an additional escape character.

Daniel R.
  • 774
  • 1
  • 7
  • 19
1

I guess replacing csvFilePrinter.printRecord("\n"); with csvFilePrinter.println(); does the job. println() will output lines separator, so you will get completely empty line without quotes.

Hope it helps!

Sergey Prokofiev
  • 1,815
  • 1
  • 12
  • 21
0

You define the CSVFilePrinter with

CSVFormat.DEFAULT.withRecordSeparator("\n")

so for each record an additional \n will be appended. You then print three records: "data1", "\n", "data2"

This will results in "data1\n\n\ndata2\n", which is exactly the result you get.

Just replace the second record with "".

Sentry
  • 4,102
  • 2
  • 30
  • 38
  • I agree with your logic. I have 1 question. Why " is displayed at those blank lines? – Radhika Kulkarni Mar 21 '18 at 13:33
  • @RadhikaKulkarni You're right, I can't explain that. I thought that you just wanted to emphasize the empty lines. Is it a single double quote (") or two single quotes ('')? In the latter case, this might be to denote an empty value – Sentry Mar 21 '18 at 17:43