Skip to content

Instantly share code, notes, and snippets.

@lpbove
Created May 3, 2017 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lpbove/4c7b5c0532fdc484daabd4998e72834a to your computer and use it in GitHub Desktop.
Save lpbove/4c7b5c0532fdc484daabd4998e72834a to your computer and use it in GitHub Desktop.
public CSVProcessor(String path, String regex)throws CSVProcessorException{
try{
br = new BufferedReader(new FileReader(path));
}catch(java.io.FileNotFoundException e){
throw new CSVProcessorException("error path");
}
this.path=path;
this.regex=regex;
readFile();
}
private void readFile()throws CSVProcessorException{
try {
String line = br.readLine();
while (line != null) {
alRows.add(checkFields(line.split(regex)));
line=br.readLine();
}
}catch(IOException e){
throw new CSVProcessorException("error reading");
}
}
/**For each position of the split(line) looks for (")
**if it has (") -> concatenates next position until it finds another (")
**it sets the concatenated positions to 'null'
**calls the function removeNulls() which returns an ArrayList without nulls and ready to be added to alRows
**/
private ArrayList checkFields(String[] line){
for(int i=0; i<line.length; i++){
if(line[i].contains("\"")){
int next=i+1;
line[i]+=regex; //Formatting: adds first delimiter character.
while(!line[next].contains("\"")){
line[i]+=line[next]+regex;
line[next]=null;
next++;
}
line[i]+=line[next]; //Concatenates last position when the while block breaks..
line[next]=null;
i=next;
}
}
return removeNulls(line);
}
private ArrayList removeNulls(String[] line){
ArrayList alLine = new ArrayList();
for(int i=0; i<line.length; i++){
if(line[i]!=null){
alLine.add(line[i]);
}
}
return alLine;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment