Skip to content

Instantly share code, notes, and snippets.

@Kagre
Created September 23, 2020 23:47
Show Gist options
  • Save Kagre/40aad4376b0d56dc9740a83da99f7c74 to your computer and use it in GitHub Desktop.
Save Kagre/40aad4376b0d56dc9740a83da99f7c74 to your computer and use it in GitHub Desktop.
RFC 4180 Compliant - OpenCSV Implementation
import com.opencsv.*;
import java.io.*;
class Example1{
public static void main(String[] args)throws Exception{
String DATA_FILE = "TestCSVparse.win.csv";
char DELIMITER = ',';
char QUOTE = '\"';
int SKIP_LINES = 0;
//Simply use the RFC 4180 compatable version
RFC4180Parser parser = new RFC4180ParserBuilder()
.withSeparator(DELIMITER)
.withQuoteChar(QUOTE)
.build();
CSVReader reader = new CSVReaderBuilder(
new BufferedReader(
new InputStreamReader(
new FileInputStream(DATA_FILE))))
.withSkipLines(SKIP_LINES)
.withCSVParser(parser)
.build();
System.out.println("Example1: " + DATA_FILE);
String[] line = reader.readNext();int i;
while(line!=null){
for(i=0;i<line.length-1;i++){
System.out.print(line[i]+"|");
}
System.out.println(line[i]);
line = reader.readNext();
}
}
}
import com.opencsv.*;
import java.io.*;
class Example2{
public static void main(String[] args)throws Exception{
String DATA_FILE = "TestCSVparse.win.csv";
char DELIMITER = ',';
char QUOTE = '\"';
int SKIP_LINES = 0;
CSVParser parser = new CSVParserBuilder()
.withSeparator(DELIMITER)
.withQuoteChar(QUOTE)
.build();
//Correct the issue as it's being read from the file.
FilterReader CustomFilter = new FilterReader(
new BufferedReader(
new InputStreamReader(
new FileInputStream(DATA_FILE)))){
protected boolean EscapeStateToggle=false;
@Override
public int read() throws IOException{
if(EscapeStateToggle){
EscapeStateToggle = false;
return ((int) '\\');
}
int ret = super.read();
EscapeStateToggle = ret == ((int) '\\');
return ret;
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException{
int ret,i;
for(i=0;i<len;i++){
ret = this.read();
if(ret<0){return (i==0)?-1:i;}
cbuf[off+i]=(char)ret;
}
return i;
}
@Override
public int read(char[] cbuf) throws IOException{
return this.read(cbuf,0,cbuf.length);
}
};
CSVReader reader = new CSVReaderBuilder(CustomFilter)
.withSkipLines(SKIP_LINES)
.withCSVParser(parser)
.build();
System.out.println("Example2: "+DATA_FILE);
String[] line = reader.readNext();int i;
while(line!=null){
for(i=0;i<line.length-1;i++){
System.out.print(line[i]+"|");
}
System.out.println(line[i]);
line = reader.readNext();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment