1 42 43 package org.jfree.data.io; 44 45 import java.io.BufferedReader ; 46 import java.io.IOException ; 47 import java.io.Reader ; 48 import java.util.List ; 49 50 import org.jfree.data.category.CategoryDataset; 51 import org.jfree.data.category.DefaultCategoryDataset; 52 53 58 public class CSV { 59 60 61 private char fieldDelimiter; 62 63 64 private char textDelimiter; 65 66 70 public CSV() { 71 this(',', '"'); 72 } 73 74 82 public CSV(char fieldDelimiter, char textDelimiter) { 83 this.fieldDelimiter = fieldDelimiter; 84 this.textDelimiter = textDelimiter; 85 } 86 87 96 public CategoryDataset readCategoryDataset(Reader in) throws IOException { 97 98 DefaultCategoryDataset dataset = new DefaultCategoryDataset(); 99 BufferedReader reader = new BufferedReader (in); 100 List columnKeys = null; 101 int lineIndex = 0; 102 String line = reader.readLine(); 103 while (line != null) { 104 if (lineIndex == 0) { columnKeys = extractColumnKeys(line); 106 } 107 else { extractRowKeyAndData(line, dataset, columnKeys); 109 } 110 line = reader.readLine(); 111 lineIndex++; 112 } 113 return dataset; 114 115 } 116 117 124 private List extractColumnKeys(String line) { 125 List keys = new java.util.ArrayList (); 126 int fieldIndex = 0; 127 int start = 0; 128 for (int i = 0; i < line.length(); i++) { 129 if (line.charAt(i) == this.fieldDelimiter) { 130 if (fieldIndex > 0) { String key = line.substring(start, i); 133 keys.add(removeStringDelimiters(key)); 134 } 135 start = i + 1; 136 fieldIndex++; 137 } 138 } 139 String key = line.substring(start, line.length()); 140 keys.add(removeStringDelimiters(key)); 141 return keys; 142 } 143 144 151 private void extractRowKeyAndData(String line, 152 DefaultCategoryDataset dataset, 153 List columnKeys) { 154 Comparable rowKey = null; 155 int fieldIndex = 0; 156 int start = 0; 157 for (int i = 0; i < line.length(); i++) { 158 if (line.charAt(i) == this.fieldDelimiter) { 159 if (fieldIndex == 0) { String key = line.substring(start, i); 161 rowKey = removeStringDelimiters(key); 162 } 163 else { Double value = Double.valueOf( 165 removeStringDelimiters(line.substring(start, i)) 166 ); 167 dataset.addValue( 168 value, rowKey, 169 (Comparable ) columnKeys.get(fieldIndex - 1) 170 ); 171 } 172 start = i + 1; 173 fieldIndex++; 174 } 175 } 176 Double value = Double.valueOf( 177 removeStringDelimiters(line.substring(start, line.length())) 178 ); 179 dataset.addValue( 180 value, rowKey, (Comparable ) columnKeys.get(fieldIndex - 1) 181 ); 182 } 183 184 192 private String removeStringDelimiters(String key) { 193 String k = key.trim(); 194 if (k.charAt(0) == this.textDelimiter) { 195 k = k.substring(1); 196 } 197 if (k.charAt(k.length() - 1) == this.textDelimiter) { 198 k = k.substring(0, k.length() - 1); 199 } 200 return k; 201 } 202 203 } 204 | Popular Tags |