Skip to content

Instantly share code, notes, and snippets.

@cab404
Created February 25, 2017 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cab404/07724b3cdc1759cb62bf091bb2c4a440 to your computer and use it in GitHub Desktop.
Save cab404/07724b3cdc1759cb62bf091bb2c4a440 to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* Simple symbol CSV reader class.
*
* @author cab404
*/
public class CSVReader {
private final static int INROW = 0;
private final static int INSTRING = 1;
private final static int ENDSTRING = 2;
private List<List<String>> table = new LinkedList<List<String>>();
private List<String> currentRow = new ArrayList<String>();
private StringBuilder buff = new StringBuilder();
private int state = 0;
private final char textDelimeter;
private final char rowDelimeter;
private final char separator;
public CSVReader(char separator, char textDelimeter) {
this.textDelimeter = textDelimeter;
this.rowDelimeter = '\n';
this.separator = separator;
}
public CSVReader(char separator, char textDelimeter, char rowDelimeter) {
this.textDelimeter = textDelimeter;
this.rowDelimeter = rowDelimeter;
this.separator = separator;
}
/**
* Parses next chunk of data.
*/
public void read(CharSequence sequence) {
for (int i = 0; i < sequence.length(); i++) {
char ch = sequence.charAt(i);
switch (state) {
case INROW:
if (ch == rowDelimeter) {
flushRow();
continue;
}
if (ch == textDelimeter) {
state = INSTRING;
continue;
}
if (ch == separator) {
flushCell();
continue;
}
buff.append(ch);
continue;
case INSTRING:
if (ch == textDelimeter) {
state = ENDSTRING;
continue;
}
buff.append(ch);
continue;
case ENDSTRING:
if (ch == rowDelimeter) {
flushRow();
continue;
}
if (ch == separator) {
flushCell();
continue;
}
if (ch == textDelimeter) {
state = INSTRING;
buff.append(textDelimeter);
continue;
}
continue;
}
}
}
private void flushCell() {
state = INROW;
currentRow.add(buff.toString());
buff.setLength(0);
}
private void flushRow() {
flushCell();
table.add(Collections.unmodifiableList(currentRow));
currentRow = new ArrayList<String>();
}
public List<List<String>> getTable() {
return Collections.unmodifiableList(table);
}
public void read(Reader reader) throws IOException {
CharBuffer buffer = CharBuffer.allocate(256);
while (reader.read(buffer) != -1) {
buffer.flip();
read(buffer);
buffer.clear();
}
}
public void read(InputStream stream) throws IOException {
read(new InputStreamReader(stream));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment