001package org.hl7.fhir.utilities;
002
003import java.io.IOException;
004import java.io.OutputStream;
005import java.io.UnsupportedEncodingException;
006
007public class CSVWriter extends TextStreamWriter {
008
009  public CSVWriter(OutputStream out) throws UnsupportedEncodingException {
010    super(out);
011  }
012
013  protected String csvEscape(String s) {
014    if (s==null)
015      return "";
016    else if (s.contains("\""))
017      return s.substring(0,s.indexOf("\"")) + "\"" + csvEscape(s.substring(s.indexOf("\"")+1));
018    else if (s.contains(","))
019      return "\""+s+"\"";
020    else
021      return s;
022  }
023  
024
025  public void line(String... fields) throws IOException {
026    StringBuilder b = new StringBuilder();
027    boolean first = true;
028    for (String s : fields) {
029      if (first)
030        first = false;
031      else
032        b.append(",");
033      b.append(csvEscape(s));
034    }
035    ln(b.toString());
036  }
037  
038}