在文本字段中使用java - 逗号分隔符读取csv文件 [英] read csv file with java - comma delimiter in text field
问题描述
我有一个逗号分隔的CSV文件包含纳斯达克符号。我使用Scanner读取文件
s = new Scanner(new File(C:\\\\ nasdaq_companylist.csv ))。useDelimiter(\\s *,\\s *);
我得到第二个字段的异常。问题是这个字段,文件包含逗号,例如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
pre>
如何避免这个问题?
我的代码是:列表< theList = new ArrayList< Stock>();
StringBuilder sb = new StringBuilder();
//获取标题
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));}
>
解决方案除非这是家庭作业,否则你不应该自己解析CSV。使用现有库之一。例如: http://commons.apache.org/sandbox/csv/
或者googlejava csv parser并选择另一个。
但是如果你想实现逻辑你自己应使用正则表达式的否定前瞻功能(请参阅 http://download.oracle.com/javase/1,5.0/docs/api/java/util/regex/Pattern.html )
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)
这篇关于在文本字段中使用java - 逗号分隔符读取csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!