81,092
社区成员
发帖
与我相关
我的任务
分享
package cn.sh.wenxuan.util.csv;
import java.io.BufferedReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
public class CsvFomatParse {
private BufferedReader br;
private boolean hasNext = true;
private char separator;
private char quotechar;
public static final char DEFAULT_SEPARATOR = ',';
public static final char DEFAULT_QUOTE_CHARACTER = '"';
public CsvFomatParse() {
this(DEFAULT_SEPARATOR, DEFAULT_QUOTE_CHARACTER);
}
public CsvFomatParse(char separator, char quotechar) {
this.separator = separator;
this.quotechar = quotechar;
}
public String [] parseLine(String line) throws Exception {
if(line == null) {
return null;
}
StringBuilder sb = new StringBuilder(line);
ArrayList list = new ArrayList();
StringBuilder buffer = new StringBuilder();
char preview = ' ';
sb.trimToSize();
int currentStatus = 0;
for(int i = 0; i < sb.capacity(); i++) {
char c = sb.charAt(i);
if(currentStatus == 0) {
if( c == quotechar) {
currentStatus = 1;
continue;
} else {
throw new Exception("WRONG FOMAT AT COLUMN " + i);
}
}
if(currentStatus == 1) {
if(c != quotechar) {
currentStatus = 2;
buffer.append(c);
} else {
currentStatus = 3;
preview = c;
//buffer.append(c);
}
continue;
}
if(currentStatus == 2) {
if(c != quotechar) {
buffer.append(c);
} else {
currentStatus = 3;
preview = c;
}
continue;
}
if(currentStatus == 3) {
if(c == quotechar) {
buffer.append(preview);
buffer.append(c);
currentStatus = 2;
} else {
if(c == separator) {
list.add(buffer.toString());
currentStatus = 4;
buffer = new StringBuilder();
} else {
throw new Exception("WRONG FOMAT AT COLUMN " + i);
}
}
continue;
}
if(currentStatus == 4) {
if(c == quotechar) {
currentStatus = 1;
} else {
throw new Exception("WRONG FOMAT AT COLUMN " + i);
}
continue;
}
}
list.add(buffer.toString());
return (String[]) list.toArray(new String[]{""});
}
public static void main(String args[]) {
CsvFomatParse parse = new CsvFomatParse();
String[] arr = null;
try {
arr = parse.parseLine("\"avmailc.exe\",\"3052\",\"Console\",\"0\",\"1,364 K\"");
} catch (Exception e) {
e.printStackTrace();
}
for(int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}