在Java中将数据从CSV解析到数组
发布时间:2020-12-14 05:49:17 所属栏目:Java 来源:网络整理
导读:我正在尝试将CS??V文件导入到可以在 Java程序中使用的数组中. CSV文件已成功导入自身,输出显示在终端上,但它会引发错误: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at CompareCSV.main(CompareCSV.java:19) 在末尾.另外,当
我正在尝试将CS??V文件导入到可以在
Java程序中使用的数组中. CSV文件已成功导入自身,输出显示在终端上,但它会引发错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at CompareCSV.main(CompareCSV.java:19) 在末尾.另外,当我尝试调用数组中的元素时,它也会显示相同的错误.我的代码如下: import java.io.*; import java.util.*; public class CompareCSV { public static void main(String[] args) { String fileName = "sampledata1.csv"; try { BufferedReader br = new BufferedReader( new FileReader(fileName)); String strLine = null; StringTokenizer st = null; int lineNumber = 0,tokenNumber = 0; while((fileName = br.readLine()) != null) { lineNumber++; String[] result = fileName.split(","); for (int x=0; x<result.length; x++) { System.out.println(result[x]); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } 解决方法
使用正确的CSV解析器比自己破解错误的解决方案要好得多:
http://opencsv.sourceforge.net/
CSV不是人们可能想到的简单格式(是的,一行可以包含一个,不会分隔两个数据). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |