Parse CSV line from Reader - Java File Path IO

Java examples for File Path IO:CSV File

Description

Parse CSV line from Reader

Demo Code


//package com.java2s;

import java.io.Reader;
import java.util.List;
import java.util.Vector;

public class Main {
    /**//from www  . j  a  va 2s.co  m
     * Returns a null when the input stream is empty
     */
    public static List<String> parseLine(Reader r) throws Exception {
        int ch = r.read();
        while (ch == '\r') {
            ch = r.read();
        }
        if (ch < 0) {
            return null;
        }
        Vector<String> store = new Vector<String>();
        StringBuffer curVal = new StringBuffer();
        boolean inquotes = false;
        boolean started = false;
        while (ch >= 0) {
            if (inquotes) {
                started = true;
                if (ch == '\"') {
                    inquotes = false;
                } else {
                    curVal.append((char) ch);
                }
            } else {
                if (ch == '\"') {
                    inquotes = true;
                    if (started) {
                        // if this is the second quote in a value, add a quote
                        // this is for the double quote in the middle of a value
                        curVal.append('\"');
                    }
                } else if (ch == ',') {
                    store.add(curVal.toString());
                    curVal = new StringBuffer();
                    started = false;
                } else if (ch == '\r') {
                    //ignore LF characters
                } else if (ch == '\n') {
                    //end of a line, break out
                    break;
                } else {
                    curVal.append((char) ch);
                }
            }
            ch = r.read();
        }
        store.add(curVal.toString());
        return store;
    }

    public static List<String> parseLine(Reader r, boolean t)
            throws Exception {
        int ch = r.read();
        if (ch < 0) {
            return null;
        }
        Vector<String> store = new Vector<String>();
        StringBuffer curVal = new StringBuffer();
        while (ch != '\r') {
            if (ch == 32 || ch == '\r' || ch == '\n') {
                ch = r.read();
                continue;
            } else if (ch < 0) {
                return null;
            } else if ((char) ch != ',') {
                curVal.append((char) ch);
            } else if (ch == ',') {
                store.add(curVal.toString());
                curVal = new StringBuffer();
            } else if (ch == '\n') {
                //end of a line, break out
                break;
            } else {
                curVal.append((char) ch);
            }
            ch = r.read();
        }

        store.add(curVal.toString());

        return store;
    }
}

Related Tutorials