I have a comma separated CSV file contains NASDAQ symbols . I use Scanner to read a file
s = new Scanner(new File("C:\\nasdaq_companylist.csv")).useDelimiter("\\s*,\\s*");
I’m getting exception on second field .The problem is that this field , like some others fields in file contain commas too, for example “1-800 FLOWERS.COM, Inc.”:
FLWS,"1-800 FLOWERS.COM, Inc.",2.8,76022800,n/a,1999,Consumer Services,Other Specialty Stores,http://www.nasdaq.com/symbol/flws
How to avoid this problem ?
My code is :
List<Stock> theList = new ArrayList<Stock>();
StringBuilder sb = new StringBuilder();
//get the title
String title = s.nextLine();
System.out.println("title: "+title);
while (s.hasNext())
{
String symbol = s.next();
String name = s.next();
double lastSale = s.nextDouble();
long marketCap = s.nextLong();
String adr =s.next();
String ipoYear=s.next();
String sector=s.next();
String industry = s.next();
String summaryQuote = s.next();
theList.add(newStock(symbol,lastSale));}
Thanks
Unless this is homework you should not parse CSV yourself. Use one of existing libraries. For example this one: http://commons.apache.org/sandbox/csv/
Or google “java csv parser” and choose another.
But if you wish to implement the logic yourself you should use negative lookahead feature of regular expressions (see http://download.oracle.com/javase/1,5.0/docs/api/java/util/regex/Pattern.html)