1 30 31 32 package org.hsqldb.util; 33 34 import java.io.File ; 35 import java.io.FileOutputStream ; 36 import java.io.IOException ; 37 import java.io.OutputStreamWriter ; 38 39 50 public class CSVWriter { 51 52 private String newline = System.getProperty("line.separator"); 53 private OutputStreamWriter writer = null; 54 private int nbrCols = 0; 55 private int nbrRows = 0; 56 57 63 public CSVWriter(File file, String encoding) throws IOException { 64 65 if (encoding == null) { 66 encoding = System.getProperty("file.encoding"); 67 } 68 69 FileOutputStream fout = new FileOutputStream (file); 70 71 writer = new OutputStreamWriter (fout, encoding); 72 } 73 74 79 public void writeHeader(String [] header) throws IOException { 80 81 this.nbrCols = header.length; 82 83 doWriteData(header); 84 } 85 86 92 public void writeData(String [] data) throws IOException { 93 doWriteData(data); 94 } 95 96 99 public void close() throws IOException { 100 this.writer.close(); 101 } 102 103 private void doWriteData(String [] values) throws IOException { 104 105 for (int i = 0; i < values.length; i++) { 106 if (i > 0) { 107 this.writer.write(";"); 108 } 109 110 if (values[i] != null) { 111 this.writer.write("\""); 112 this.writer.write(this.toCsvValue(values[i])); 113 this.writer.write("\""); 114 } 115 } 116 117 this.writer.write(newline); 118 119 this.nbrRows++; 120 } 121 122 private String toCsvValue(String str) { 123 124 StringBuffer sb = new StringBuffer (); 125 126 for (int i = 0; i < str.length(); i++) { 127 char c = str.charAt(i); 128 129 sb.append(c); 130 131 switch (c) { 132 133 case '"' : 134 sb.append('"'); 135 break; 136 } 137 } 138 139 return sb.toString(); 140 } 141 } 142 | Popular Tags |