CSV parser. It maybe work for CSV file that is exported from Excel. but it doesn’t support multiline cell.
hpackage jp.underthetree.csvparser;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class CsvFile {
private List rows = new ArrayList();
// read from stream
public static CsvFile createFromStream(InputStream st) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(st));
CsvFile file = new CsvFile();
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
file.getRows().add(new CsvRow(line));
}
return file;
}
// list implementation of CsvRow
public List getRows() {
return rows;
}
// output to stream
public void writeToStream(OutputStream st) throws IOException {
BufferedWriter wri = new BufferedWriter(new OutputStreamWriter(st));
for (Iterator it = getRows().iterator(); it.hasNext();) {
wri.write(((CsvRow)it.next()).toCsvString());
}
}
public String toString() {
return rows.toString();
}
public static class CsvRow {
private List cells = new ArrayList();
public CsvRow() {}
// read from line
public CsvRow(String line) {
final StringBuffer buf = new StringBuffer();
boolean openQuot = false;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
openQuot ^= (c == '"');
if (!openQuot && c == ',') {
this.cells.add(new CsvCell(buf.toString()));
buf.setLength(0);
} else {
buf.append(c);
}
}
}
// output comma separated line
public String toCsvString() {
StringBuffer buf = new StringBuffer();
Iterator it = getCells().iterator();
for (buf.append((String)it.next());
it.hasNext();
buf.append(",").append((String)it.next()));
return buf.toString();
}
// list implementation of CsvCell
public List getCells() {
return cells;
}
public String toString() {
return cells.toString();
}
}
public static class CsvCell {
public static final String QUOT_CHAR = """;
public static final String QUOT_ESCAPE = """";
private final String rawData;
public CsvCell(String data) {
rawData = data;
}
// cook cell's "
public static CsvCell createCsvCellFromFormat(String data) {
StringBuffer buf = new StringBuffer();
char lastChar = 0;
for (int i = 0; i < data.length(); i++) {
char c = data.charAt(i);
if ((lastChar != '"' && c != '"') ||
lastChar == '"' && c == '"') {
buf.append(c);
}
lastChar = c;
}
return new CsvCell(buf.toString());
}
// output escaped string of cell data
public String toCsvString() {
if (rawData.indexOf(QUOT_CHAR) > 0) {
return quote(rawData.replace(QUOT_CHAR, QUOT_ESCAPE));
} else if (rawData.indexOf(",") > 0) {
return quote(rawData);
}
return rawData;
}
// output contents text
protected String quote(String str) {
return QUOT_CHAR.concat(rawData).concat(QUOT_CHAR);
}
public String toString() {
return rawData;
}
}
}
コメントを残す