繁体   English   中英

如何使用CSV文件中每一行的数据在Java中创建对象

[英]How to create objects in Java using data from each line from a CSV file

我创建了一个类,该类具有带字符串行的构造函数,在对数据进行一些处理之后将其变成对象。

我需要一次将CSV中的一行数据馈入构造函数中,以为文件的每一行创建一个对象。 但是,从我所有的搜索中,我无法弄清楚如何创建这些对象,就像我学到的那样,要创建对象就必须命名这些对象。 有没有一种方法可以创建对象数组,因此不必命名每个对象? 例如,第一行就像Object [0]等等?


public class Object{
  String Name, Example, Example2;
  Object(String data){
    //Data manipulation to get into Name Example and Example2 creating an
    //object
  }

  public String getName{
    return Name;
  }
}

public class ObjectFeed{
  //This is where I would open the file and feed it line by line into the  
  //object class
}

我应该能够在任何行号上使用为Object类创建的getter方法,并且它应该获取该信息。 我只是不了解如何将数据输入对象并创建多个对象。

如果数据来自CSV,则每个单元格应以逗号分隔,因此您应该能够获取输入字符串data并将其分割。

可以这样完成:

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

然后,您可以将csvList每个元素分配为对象的属性之一,并遍历其所有元素以生成对象列表。

List<YourObject> objects = new List<YourObject>();

// increment i by the how many properties YourObject has
for (int i = 0; i < csvList.length; i += 2) {
   YourObject obj = new YourObject();
   obj.FirstProperty = csvList[i];
   obj.SecondProperty = csvList[i+1];
   ...
   objects.add(obj);
}

我会做这样的事情:

public void createYourObjects() {

  List<String> lines = // however you are reading lines from the CSV file

  List<YourObject> objects = new ArrayList<>();
  for(String line in lines) {
    objects.add(methodB(line);
  }
}

public YourObject createYourObjectFrom(String line) {
  List<String> columns = line.spilt(",");
  return new YourObject(columns.get(0), columns.get(1) ..... columns(n-1));  // where n is the size of the list n-1 is the index of the last item in the list
}

它有点伪代码,但我认为它说明了基本思想。 通过使用单独的方法构造对象,可以分离关注点,从而将对象列表的创建与CSV文件的结构隔离开。
它还为您提供了提供所需的任何错误或特殊情况处理的地方。

在现实世界中,您可能需要处理不同类型的数据,从String转换为int ,以及当列为空时。 在列为空的情况下,您将获得较小的列列表,并且必须进行处理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM