Created
May 3, 2017 02:39
-
-
Save lpbove/4c7b5c0532fdc484daabd4998e72834a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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