Skip to content

Instantly share code, notes, and snippets.

@sipadan2003
Created September 20, 2017 01:55
Show Gist options
  • Save sipadan2003/07bdecafc480a402229b0adda189ec0d to your computer and use it in GitHub Desktop.
Save sipadan2003/07bdecafc480a402229b0adda189ec0d to your computer and use it in GitHub Desktop.
Simple CSV file reader
package tv.minato.common.csv
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CSVReader implements AutoCloseable {
private final BufferedReader r;
private char splitter = ',';
private char encloser = '\"';
private String lineSeparator = System.lineSeparator();
public CSVReader(BufferedReader r){
this.r = r;
}
@Override public void close() throws IOException {
r.close();
}
public CSVReader splitter(char c){
this.splitter = c;
return this;
}
public CSVReader encloser(char c){
this.encloser = c;
return this;
}
public CSVReader lineSeparator(String s){
this.lineSeparator = s;
return this;
}
public List<String> readRow() throws IOException {
final List<String> row = new ArrayList<>();
final StringBuilder sb = new StringBuilder();
boolean enclosed = false; //囲まれている状態か
do {
final String line = r.readLine();
//終端に達した
if(line == null){
if(sb.length() > 0){
row.add(sb.toString());
return row;
}else if(row.size() > 0){
return row;
}
return null;
}
//1行文処理する
char[] buf = line.toCharArray();
for(int i=0; i<buf.length; i++){
final char c = buf[i];
if(c == encloser){
final boolean isNextQuote = isNextEncloser(buf, i+1);
if(isNextQuote == true){
i++;
sb.append(encloser);
sb.append(encloser);
}else{
enclosed = !enclosed;
}
}else if(c == splitter){
if(enclosed == true){
sb.append(c);
}else{
row.add(sb.toString());
sb.setLength(0);
}
}else{
sb.append(c);
}
}
//行が終了したが、囲まれている状態
if(enclosed == true){
sb.append(lineSeparator);
}else if(sb.length() > 0){
row.add(sb.toString());
}
}while(enclosed == true);
return row;
}
/**
*次の文字がencloserかどうかを判定します。
*@param buf 文字のバッファ
*@param index 文字の位置
*@return encloserかどうか
*/
private boolean isNextEncloser(char[] buf, int index){
return (index == buf.length) ? false : (buf[index] == encloser);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment