简体   繁体   English

用Java解析文件并检测模式

[英]Parsing file and detection of pattern in Java

My problem is quite simple, i am parsing a CSV file, line after line and i want to get the values of the columns. 我的问题很简单, 我正在逐行解析CSV文件,我想获取列的值。 The separators used are simply " ; ", but my file can have quite a lot of columns, and they won't be always in the same order. 所使用的分隔符只是“ ; ”,但是我的文件可以包含很多列,而且它们的顺序不一定总是相同的。

So as example for my .CSV file : 因此,以我的.CSV文件为例:

time;columnA;columnB,ColumnC
27-08-2013 14:43:00; this is a text; this too; same here

And i would like to be able to get all the values of time, columnA, columnB and columnC. 而且我希望能够获得time,columnA,columnB和columnC的所有值。 What would be the easiest way? 最简单的方法是什么?

I used StringUtils.countMatches(input, ";"); 我使用了StringUtils.countMatches(input, ";"); to get the number of separators i have. 得到我有分隔符的数量。 I started trying to make a String index[][] = {{"time", "columnA", "columnB", "columnC"}{}}; 我开始尝试使String index[][] = {{"time", "columnA", "columnB", "columnC"}{}}; And my plan was to fill this with the number of " ; " before each other variable, so that i could easily now which result stands for which variable. 我的计划是在每个变量前都加上“ ; ”号,这样我现在就可以轻松地将哪个结果代表哪个变量。

But now i'm quite stuck... 但是现在我很困...

If you want me to show more of my code, i can. 如果您希望我显示更多代码,可以。 Hope that someone can help me ! 希望有人能帮助我! :) :)

(sorry for the poor english). (对不起,英语不好)。

You can simply use split() method 您可以简单地使用split()方法

For instance: 例如:

Scanner aScanner = ...
ArrayList<String> L = new ArrayList<String>();
while(aScanner.hasNextLine()){
    L.add(aScanner.nextLine());
}
int rows = L.size();
String[][] S = new String[rows][];
for (int i = 0; i < rows; i++) {
    S[i] = L.get(i).split(";");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM