开发者

I need something like a DataTable in Java

开发者 https://www.devze.com 2023-03-27 05:39 出处:网络
I have looked around but cannot seem to find anything quite like i need. I need to read in a CSV file with column headers eg:

I have looked around but cannot seem to find anything quite like i need.

I need to read in a CSV file with column headers eg:

NAME;AGE;HEIGHT
dan;36;180
john;31;181
ben;30;190

what object can i parse it into read where i can then reference it like so:

object.name = (string) someSortOfDataStructure["NAME"];
object.name = (int) someSortOfDataStructure["AGE"];

or

object.name = someSortOfDataStructure.getColumn("NAME");

In C# I can do this with some开发者_JAVA技巧thing like a DataTable / DataRow.


Think OOP. You need to create a Person class with the properties name, age and height.

public class Person {

  private String name;
  private String age;
  private String height;

  // Getter and setter methods...
}

Next, read CSV file line by line using a BufferedReader. For each line you want to split the line using line.split(";"); to give you an String[] containing the tokens.

For the line you can now create a Person from the tokens;

Person person = new Person();
person.setName(tokens[0]);
person.setAge(tokens[1]);
person.setHeight(tokens[2]);

Note that this assumes the positions of the columns. If you want to remove this assumption you need to Map the header to a position.

String headerLine = "NAME;AGE;HEIGHT";
String[] headers = headerLine.split(";");
Map<String,Integer> map = new HashMap<String,Integer>();
for (int i=0; i<headers.length; i++) {
  map.put(headers[i], i);
}

You can then get the position of a column by it's name;

Person person = new Person();
person.setName(tokens[map.get("NAME")]);
person.setAge(tokens[map.get("AGE")]);
person.setHeight(tokens[map.get("HEIGHT")]);

Table type classes are an anti-pattern. They tend to appear when the programmer can't be bothered to think in terms of Objects. I often see Table classes in legacy java applications and its a real PITA to work with them. Don't do it.


Okay... you can use default table model. It is made to support swing tables, I am not sure if it will be able to help you or not. http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/table/DefaultTableModel.html


The Guava library has a Table interface which should be what you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消