2013-01-10 113 views
0

我使用OpenCSV解析Java中的CSV文件,並希望獲得(例如)文件中每行的第三個元素的狀態數爲「UDP」或「TCP」。我如何從現在的位置選擇具體數據並將其存儲在單獨的變量中? (即 - 如果在每行的第三個元素中包含的文件中包含20個「UDP」實例,則顯示計數爲20的整數)到目前爲止,我只能打印出文件的全部內容,即I我解析如下:使用OpenCSV提取Java中CSV數據的統計信息

try { 
    CSVReader reader = new CSVReader(new FileReader(filePath), ','); 

    // Reads the complete file into list of tokens. 
    List<String[]> rowsAsTokens = null; 
    try { 
     rowsAsTokens = reader.readAll(); 
    } 
    catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

    Iterator<String[]> rowsAsTokensIt = rowsAsTokens.iterator(); 
    while (rowsAsTokensIt.hasNext()) { 
     for (String token : rowsAsTokensIt.next()) { 
      System.out.print(token + " "); 
     } 
     System.out.println(); 
    } 
} 
+0

你的意思是你想知道如何得到一個數組的第n個元素? –

+0

是的,我想知道如何獲得它,以及如何使用「IF」語句或適合將數據存儲在單獨變量中的方式從中過濾出特定數據。 –

回答

0

你在問什麼是非常非常基本的Java或C或C++,我建議你閱讀關於Java的東西。

double sum = 0; 
for(String[] row: rowsAsTokens) { 
    // check the first row is HELLO 
    if(row[0].equals("HELLO")) { 
     // get the second row as a double 
     sum += Double.parseDouble(row[1]); 
    } 
} 
// print the grand total once at the end 
System.out.println(sum); 
+0

來自此的輸出是行[0]爲true的實例數的行[1]的內容。我正在尋找滿足行[0] .equals(「HELLO」)的條件時的總數。 –

+0

@THOCOCOR我改變了。再次,這是非常基本的東西。 –

+0

仍然沒有得到正確的結果。根據你的代碼,我得到了行[0]中包含「HELLO」的每個實例的輸出。我正在尋找總計的一個結果,而不是總計。我知道這是基本的東西,你不需要重申。我現在還沒有編程一段時間,解決這樣的問題有助於我走上熟練的道路。謝謝。 –

0

我會保持計數在HashMap。我也避免使用readAll(),所以你不必重複數據兩次。

只需要聲明地圖

Map<Object, Integer> countMap = new HashMap<String, Integer>(); 

然後爲你維護在第3列

String [] row; 
while ((row = reader.readNext()) != null) { 
    String value = row[2]; // value in 3rd column 

    // default count to 0 if not in map 
    Integer count = countMap.get(value) != null ? countMap.get(value) : 0; 

    // increment count in map 
    countMap.put(value, count + 1); 

} 

System.out.println("UDP count: " + countMap.get("UDP")); 
System.out.println("TCP count: " + countMap.get("TCP")); 

正如你可以使用Super CSV,它具有高度的靈活性/配置替代遇到的每一個值的計數。上述解決方案適用於一個微不足道的場景(例如保持1列的計數),但如果您不斷添加越來越多的功能,則很容易變得不可讀。 Super CSV具有強大的cell processor API,可自動執行轉換和約束條件,從而大大簡化此操作。例如,你可以編寫一個custom cell processor,它維護它遇到的每個唯一列值的計數。

package example; 

import java.util.Map; 

import org.supercsv.cellprocessor.CellProcessorAdaptor; 
import org.supercsv.cellprocessor.ift.CellProcessor; 
import org.supercsv.util.CsvContext; 

public class Counter extends CellProcessorAdaptor { 

    private final Map<Object, Integer> countMap; 

    public Counter(final Map<Object, Integer> countMap) { 
    super(); 
    if (countMap == null){ 
     throw new IllegalArgumentException("countMap should not be null"); 
    } 
    this.countMap = countMap; 
    } 

    public Counter(final Map<Object, Integer> countMap, final CellProcessor next) { 
    super(next); 
    if (countMap == null){ 
     throw new IllegalArgumentException("countMap should not be null"); 
    } 
    this.countMap = countMap; 
    } 

    @Override 
    public Object execute(Object value, CsvContext context) { 

    validateInputNotNull(value, context); 

    // get count from map (default to 0 if doesn't exist) 
    Integer count = countMap.get(value) != null ? countMap.get(value) : 0; 

    countMap.put(value, count + 1); 

    return next.execute(value, context); 
    } 

} 

然後用處理器上的第3列

package example; 

import java.io.IOException; 
import java.io.StringReader; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 

import org.supercsv.cellprocessor.ParseDate; 
import org.supercsv.cellprocessor.constraint.NotNull; 
import org.supercsv.cellprocessor.ift.CellProcessor; 
import org.supercsv.io.CsvListReader; 
import org.supercsv.io.ICsvListReader; 
import org.supercsv.prefs.CsvPreference; 

public class Counting { 

    private static final String CSV = "id,time,protocol\n" + "1,01:23,UDP\n" 
     + "2,02:34,TCP\n" + "3,03:45,TCP\n" + "4,04:56,UDP\n" 
     + "5,05:01,TCP"; 

    public static void main(String[] args) throws IOException { 

    final Map<Object, Integer> countMap = new HashMap<Object, Integer>(); 

    final CellProcessor[] processors = new CellProcessor[] { 
     new NotNull(), // id 
     new ParseDate("hh:mm"), // time 
     new NotNull(new Counter(countMap)) // protocol 
    }; 

    ICsvListReader listReader = null; 
    try { 
     listReader = new CsvListReader(new StringReader(CSV), 
      CsvPreference.STANDARD_PREFERENCE); 

     listReader.getHeader(true); 

     List<Object> row; 
     while ((row = listReader.read(processors)) != null) { 
     System.out.println(row); 
     } 

    } finally { 
     listReader.close(); 
    } 

    System.out.println("Protocol count = " + countMap); 

    } 

} 

輸出:

[1, Thu Jan 01 01:23:00 EST 1970, UDP] 
[2, Thu Jan 01 02:34:00 EST 1970, TCP] 
[3, Thu Jan 01 03:45:00 EST 1970, TCP] 
[4, Thu Jan 01 04:56:00 EST 1970, UDP] 
[5, Thu Jan 01 05:01:00 EST 1970, TCP] 
Protocol count = {UDP=2, TCP=3}