holdtom
使用存在严重问题String[] strArr=line.split(",");为了分析CSV文件,这是因为数据值中可能包含逗号,在这种情况下,您必须对它们加引号,而忽略引号之间的逗号。有一个非常简单的方法可以解析此:/*** returns a row of values as a list* returns null if you are past the end of the input stream*/public static List parseLine(Reader r) throws Exception { int ch = r.read(); while (ch == '\r') { //ignore linefeed chars wherever, particularly just before end of file ch = r.read(); } if (ch<0) { return null; } Vector store = new Vector(); 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;}这种方法有很多优点。请注意,每个字符仅被触摸一次。没有向前读取,没有向后推缓冲区,等等。没有向前搜索到行尾,然后在解析之前复制了该行。此解析器仅从流中工作,并且每个字符串值创建一次。它适用于标题行和数据行,您只需要处理返回的列表即可。您为它提供了一个阅读器,因此基础流已使用您选择的任何编码转换为字符。流可以来自任何来源:文件,HTTP帖子,HTTP get,您可以直接解析流。这是一个静态方法,因此没有要创建和配置的对象,并且当返回时,没有任何内存被保留。您可以找到有关此代码的完整讨论,以及为什么在我的主题为CSV文件的唯一类的博客文章中首选此方法 。