Android,通过换行拆分.csv?

时间:2014-09-11 10:25:18

标签: java android eclipse csv

首先,我是英国人的废话。我希望没关系; 我有一个小项目要做:解析.csv文件:

典型的.csv文件

The recording starts at 2014,Sep,9,4:40:24 PM
accX,accY,accZ,gX,gY,gZ,
-0.3958511,0.014643669,10.037987,-13.17548,-2.3169785,-3.2103431,
-0.29875562,0.014643669,10.037987,-53.558975,0.22515106,-36.11273,
-0.29875562,0.014643669,10.23412,-50.653694,0.7335739,-32.481117,
The recording ends at 2014,Sep,9,4:40:29 PM

我尝试过OPENcsv库,但我无法使其工作。所以我在stackOverFlow上找到了解释,并且我使用它,它运行良好。最初,它用逗号“,”分割文件,它可以工作。

但是我把它改成了换行符,你可以看到line.split(“\ r?\ n”)。它不起作用,它实际上崩溃了。

MainActivity.java

File f = new File(path + "/" + "motionTracker/");        
            File f2 = new File(f + "/" + stringx);
try {
                fis = new FileInputStream(f2.toString());
            } catch (FileNotFoundException e1) {
                // handle exception
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
            String date = "kek";
            String value = "wow";
            String line = "lel";       
            try {
                while ((line = reader.readLine()) != null) {
                     String[] RowData = line.split("\\r?\\n");
                     date = RowData[0];
                     value = RowData[1];
                }
            }
            catch (IOException ex) {
                // handle exception
            }
            finally {
                try {
                   fis.close();
                }
                catch (IOException e) {
                    // handle exception
                }
            }

您认为问题是因为.csv文件中没有换行符吗? 或许我的代码做错了。

感谢。

1 个答案:

答案 0 :(得分:0)

使用

BufferedReader reader 

并逐行阅读您的文件

line = reader.readLine()

然后您的专线不包含换行符(&#39; \ n&#39;或&#39; \ r?\ n&#39;)... < / p>

那会发生什么?

String[] RowData = line.split("\\r?\\n");

此数组的大小必须始终为1,并且与String line

相同

所以最终

 date = RowData[0]; // equal to line
 value = RowData[1]; //index out of bounds - line has never been splitted

将抛出IndexOutOfBounds-Exception ......