如何在CSV中连续阅读并将其放入java

时间:2018-04-17 02:02:04

标签: java csv

寻找一种存储csv的方法,然后取出第一行并将数据值放在我的文本文件的某些位置,然后转到下一行。不想使用外部库或JAR。

  

我的CSV看起来像:日期,代码,时间,Code2,值为5546,3333,   5月3日,9999; 0003; 2234。 (是的,最后一个有多个输入   柱。它将有多行。

我的Csv代码是:

   Scanner scanner = new Scanner(new File ("C:\\Users\\Documents\\order.csv\\"));
   scanner.useDelimiter("\n");

   ArrayList<String> data = new ArrayList<String>();
   while (scanner.hasNext()){
       scanner.useDelimiter(",");
       data.add(scanner.next());
   }

   scanner.close();

不确定如何使用来自csv的所有元素循环遍历数组,然后将这些元素写入文本文件中。

1 个答案:

答案 0 :(得分:1)

你可以做的是一次读一行(使用NextLine),而不是一次只读一个字(下一个)

while (scanner.hasNextLine()){
   String line = scanner.nextLine();

   //you then chop up your text using the split
   String[] choppedUpText = line.split(",");
   // you can then process according to your needs here
   //e.g. convert it to a class object or add to an array.

   myList.add ( new myCustomClass( choppedUpText)); 
}

编辑:我看到你的对象可以拉伸到多行。

假设你有一个类似下面的csv

a, b, c, ddd
ddd_continued
a, b, c, ddd
a, b, c, ddd

创建一个名为my object的类

class MyObjectEntity{
  String a, b, c;
  String d=""; 
  public MyObjectEntity(String[] tokens){
     this.a = tokens[0]; ... the rest of your constructor
  }

  public void appendD(String s) { d+=s; } //used for appending the next line. 
}

然后在你的代码中。

MyObjectEntity object = null;
List<MyObjectEntity> list = new ArrayList<>();
while (scanner.hasNextLine()){
   String line = scanner.nextLine();

   if(object ==null) { //check if the object already exists?
       //no previous object.

       //you then chop up your text using the split
       String[] choppedUpText = line.split(",");
       if(choppedUpText.length ==4){ //has to have 4 parts 
           //we create the object first. 
           //then continue iterating to see if there are more parts
           object = new MyObjectEntity( choppedUpText);
       }else {
           println("Error in line: "+ line);
       }

   }else {
      //previous object exists

      if(line.contains(","){ // check if it is a new object, or a continuation of d
          //new object (save old copy to the list)
          list.add(object)

          //create a new object
          String[] choppedUpText = line.split(",");
          if(choppedUpText.length ==4){
             object = new MyObjectEntity( choppedUpText);
          }else {
             println("Error in line: "+ line);
             object = null; //reset it back to null
          }

      }else{

          //continuation of d
          object.append(line);
      }   
   } 
}
//end of loop (if object is not null, then add the last entry in)
if(object !=null) {    list.add(object);    }