集册 Java实例教程 分析读卡器中的CSV行

分析读卡器中的CSV行

欢马劈雪     最近更新时间:2020-01-02 10:19:05

533
从阅读器解析CSV行
/*来自 
 N o  w  J a v a . c o m - 时  代  Java*/


//package com.nowjava;


import java.io.Reader;

import java.util.List;

import java.util.Vector;


public class Main {

    /**

     * 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;/*时代Java - nowjava.com 提 供*/

        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 != ',') {

                curV
展开阅读全文