如何创建一个包含CSV文件字符串字符串的对象数组?

时间:2014-02-15 23:46:25

标签: java arrays class object csv

我有一些代码可以从一个csv文件中读取,该文件中包含许多人的姓氏,名字和出生年份。在csv文件中看起来像这样:

nameLast    nameFirst   birthYear
Santos      Valerio       1972
Tekulve      Kent         1947
Valentine    Fred         1935

我有一个名为Human的类,而人类也有这三个值。我想创建一个人类的数组,并从csv文件中传入我的所有数据。这样,如果[0]处的数组的第一个实例将包含三个值,其中两个用于名称,一个用于年份。这是我到目前为止的代码:

package testing.csv.files;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Human {

    String lastName;
    String firstName;
    String birthYear;

    public static void main(String[] args) {
        //.csv comma separated values
        String fileName = "C:/Users/Owner/Desktop/Data.csv";
        File file = new File(fileName); // TODO: read about File Names
        try {
            Scanner inputStream = new Scanner(file);
            inputStream.next(); //Ignore first line of titles
            while (inputStream.hasNext()){
                String data = inputStream.next(); // gets a whole line
                String[] values = data.split(",");
                System.out.println(values[2]);
            }
            inputStream.close();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

我现在所拥有的东西将打印出所有的出生年份,因为价值[2]是出生年份。我以为我可以换线

   String[] values = data.split(",");

阅读

   Human[] values = data.split(",");

然后它会自动将值lastName,firstName和birthyear分配给数组中每个对象的正确位置。但是,这样做只会产生错误消息

   incompatible types: String[] cannot be converted to Human[]

我还尝试从

更改此行之上的行
  String data = inputStream.next(); // gets a whole line

  Human data = inputStream.next(); // gets a whole line

但是我收到了同样的错误消息。

那么我做错了什么?也许我没有像我想的那样正确地定义课程,或者我的方法有什么更大的错误?请让我知道你的想法。

2 个答案:

答案 0 :(得分:0)

String类中的方法split返回一个字符串数组,而不是Human的数组。要创建Human数组,您需要将从split返回的String数组解析为人类需要的值。

class Human{
    String firstName;
    String lastName;
    int birthYear;
    public Human(String first, String last, int birthYear){
        this.firstName = first;
        this.lastName = last;
        this.birthYear = birthYear;
    }
}
int numHumansInCSV = //How many humans are in your file?
Human[] humanArray = new Human[numHumansInCSV];
int index = 0;
while (inputStream.hasNext()){
    String data = inputStream.next(); // gets a whole line
    String[] values = data.split(",");
    String lastName = values[0];
    String firstName = values[1];
    int birthYear = Integer.parseInt(values[2]);
    Human human = new Human(firstName, lastName, birthYear);
    //put human in human array.
    humanArray[index] = human;
    index += 1;
}

如果您可以使用像List这样的数据结构,那么它比数组更合适,因为您可能不知道您的CSV文件包含多少人。

此外,这个解析代码应该在它自己的类中。如果我写这个,那就是我要做的。

public class HumanCSVReader{

    public List<Human> read(String csvFile, boolean expectHeader) throws IOException{
        File file = new File(csvFile);
        Scanner scanner = new Scanner(file);
        int lineNumber = 0;
        List<Human> humans = new List<Human>();
        while(scanner.hasNextLine()){
            if(expectHeader && lineNumber==0){
                ++lineNumber;
                continue;
            }

            String line = scanner.nextLine();
            String csv = line.split(",");
            if(csv.length!=3)
                throw new IOException("Bad input in "+csvFile+", line "+lineNumber);
            String firstName = list[0];
            String lastName = list[1];
            try{
                int birthYear = Integer.parseInt(list[2]);
            }catch(NumberFormatException e){
                throw new IOException("Bad birth year in "+csvFile+", line "+lineNumber);
            }
            Human human = new Human(fistName, lastName, birthYear);
            humans.add(human);
            ++lineNumber;
        }
        return humans;
    }
}

只需使用它来加载你的人类阵列。它甚至可以处理一些基本的验证。

答案 1 :(得分:0)

首先,你的Human类需要一个构造函数。插入以下方法。

public Human(String[] str) {
  lastName = str[0];
  firstName = str[1];
  birthYear = str[2];
}

现在,您可以使用

获取Human对象,而不是字符串数组
Human someHuman = new Human(data.split(","));
相关问题