0

OpenCSVを使用してJavaでCSVファイルを解析しています。たとえば、ファイルの各行の3番目の要素が「UDP」または「TCP」のいずれかを示しているインスタンスの数を取得したいと思います。現在の場所から言及した特定のデータを選択して、別の変数に保存するにはどうすればよいですか?(つまり、各行の3番目の要素に含まれるファイル全体に「UDP」のインスタンスが20個ある場合に20のカウントを示す整数)これまでのところ、私はファイルの内容全体を印刷することしかできません。次のように解析しています:

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();
    }
}
4

2 に答える 2

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);
于 2013-01-10T16:57:50.897 に答える
0

カウントはHashMapで維持します。readAll()また、データを2回繰り返す必要がないように、使用を避けます。

地図を宣言するだけ

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"));

別の方法として、柔軟性が高く構成可能なスーパーCSVを使用することもできます。上記の解決策は、些細なシナリオ(1列のカウントを維持するなど)には問題ありませんが、機能を追加し続けると、簡単に判読できなくなる可能性があります。スーパーCSVには、変換と制約を自動化する強力なセルプロセッサAPIがあり、これを大幅に簡素化できます。

たとえば、検出した一意の列値ごとにカウントを維持するカスタムセルプロセッサを作成できます。

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}
于 2013-01-11T00:53:52.463 に答える