C# と VB.NET の質問掲示板

わんくま同盟

ASP.NET、C++/CLI、Java 何でもどうぞ

C# と VB.NET の入門サイト


(過去ログ 60 を表示中)
■34330 / )  Re[3]: java CSVファイルからクラス配列に格納したい
□投稿者/ επιστημη (1848回)-(2009/03/26(Thu) 09:01:12)
επιστημη さんの Web サイト
こんなんでえぇのかの。

--- foo.java ---
import java.io.*;
import java.util.*;

class Student {
  public int studentNum;
  public String name;
  public String hobby;
  static Student fromCSV(String line) {
    StringTokenizer tokenizer = new StringTokenizer(line,",");
    Student result = new Student();
    result.studentNum = Integer.parseInt(tokenizer.nextToken());
    result.name       = tokenizer.nextToken();
    result.hobby      = tokenizer.nextToken();
    return result;
  }
}

public class foo {

  static ArrayList<Student> readCSV(String path) throws Exception {
    ArrayList<Student> result = new ArrayList<Student>();
    BufferedReader reader = new BufferedReader(new FileReader(path));
    while ( reader.ready() ) {
      result.add(Student.fromCSV(reader.readLine()));
    }
    reader.close();
    return result;
  }

  public static void main(String[] args) {
    try {
      for ( Student s : readCSV(args[0]) ) {
        System.out.printf("#%d: %s (%s)\n", s.studentNum, s.name, s.hobby);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

--- foo.csv ---
1,episteme,C++
2,naka,C#
3,janne,VB
4,hatsune,Oracle
5,nagise,Java

--- java foo foo.csv ---
#1: episteme (C++)
#2: naka (C#)
#3: janne (VB)
#4: hatsune (Oracle)
#5: nagise (Java)

返信 編集キー/


管理者用

- Child Tree -