Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement