Reputation: 854
I write a CSV file with Open CSV (in version 2.3).
In my CSV file I want to write the following line : I choose a "hero" for this adventure
But I don't find the correct configuration and finally my line is printed, in my CSV file, like that : I choose a ""hero"" for this adventure
So my code is :
CSVWriter writer = null;
writer = new CSVWriter(outputStreamWriter,';',CSVWriter.NO_QUOTE_CHARACTER);
String[] lines = new String[4] ;
lines[0] = "Where is Brian" ;
lines[1] = "42" ;
lines[2] = "I choose a "hero" for this adventure" ;
lines[3] = "May the fourth be with you" ;
for (String line : lines ) {
writer.writeNext(line );
}
writer.close();
How can I write correctly my line ?
Maybe I must use the CSVParser class ?
Upvotes: 0
Views: 1547
Reputation: 983
You do have to escape the input but if you do not want the output escaped you can create the writer with the CSVWriter.NO_ESCAPE_CHARACTER. Here is a sample JUnit that shows what I am talking about.
@Test
public void embeddedQuoteInString() {
String[] line = {"Foo", "I choose a \\\"hero\\\" for this adventure"};
StringWriter sw = new StringWriter();
CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER);
csvw.writeNext(line);
assertEquals("\"Foo\",\"I choose a \\\"hero\\\" for this adventure\"\n", sw.toString());
}
Upvotes: 0
Reputation: 854
I find a solution to my problem, it's not the best because it's not generic, but it's work in my case. I have to call the following function :
public void replaceDoubledQuotesInFile(File file) throws IOException {
File tempFile = new File("temp.csv");
FileWriter fw = new FileWriter(tempFile);
Reader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while(br.ready()) {
String readenLine = br.readLine();
if(readenLine.contains("\"\"")){
String str1 = readenLine.replaceAll("\"\"", "!");
String str2 = str1.replaceAll("!", "\"");
fw.write(str2 + "\n");
}
else{
fw.write(readenLine + "\n");}
}
fw.close();
br.close();
fr.close();
file.delete();
tempFile.renameTo(file);
}
Upvotes: 0
Reputation: 1643
As documentation says: https://docs.oracle.com/javase/tutorial/java/data/characters.html
just use:
lines[2] = "I choose a \"hero\" for this adventure" ;
Upvotes: 1
Reputation: 26961
Escape the quotes
lines[2] = "I choose a \"hero\" for this adventure";
Or Use single quotes:
lines[2] = 'I choose a "hero" for this adventure';
Or
lines[2] = "I choose a 'hero' for this adventure";
Upvotes: 4