I am java noob and also very new to this site, so please carry me here. If I do something wrong, post it, please let me know, and I apologize in advance for everything I do, or for any bad grammar.
I need to write my own CSV parser in java that does not separate commas inside quotes. I cannot use anything related to the CSV class. 1,2,3,4 → 1 2 3 4 a, b, c ", d → ab, cd
No matter what I try, I always get an exception
import java.io.*; import java.util.*; public class csv { public static void main(String[] args) { File file = new File("csv.test"); BufferedReader buf = null; try { buf = new BufferedReader(new FileReader(file)); String str; while ((str = buf.readLine()) != null) { String[] values = null; // array for saving each split substr int c1 = 0; // counter for current position in string int c2 = 0; // counter for next space in array to save substr int c3 = 0; // location of last comma or quotation for substring creation int i = 0; // counter used later for printing while (c1 <= str.length()) { char x = str.charAt(c1); String s = Character.toString(x); if (c1 == str.length()) { values[c2] = str.substring(c3, (c1 - 1)); } else if (s == ",") { values[c2] = str.substring(c3, (c1 - 1)); c1++; c2++; c3++; } else if (s == "\"") { c1++; c3 = c1; while (s != "\"") c1++; values[c2] = str.substring(c3, (c1 - 1)); c1 = c1 + 2; c2++; c3 = c1; } else { c1++; } while (i < values.length) System.out.println("\"" + values[i] + "\""); } } } catch (Exception e) { System.out.println("Error locating test file"); } } }
I tried to cut out all the logic and testing if this is related to the file. which reads well, so logic obeys them. I looked through it and can not find anything wrong with that. I even had a friend, and he said that everything was in order. Where is the exception thrown?
source share