【问题标题】:how to read in a row in a CSV and put it in a text file in java如何在 CSV 中连续读取并将其放入 java 中的文本文件中
【发布时间】:2018-04-17 02:02:04
【问题描述】:

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

我的 CSV 看起来像:日期、代码、时间、代码 2,值为 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 的元素的数组,然后将这些元素写入文本文件。

【问题讨论】:

标签: java csv


【解决方案1】:

你可以做的是一次读一行(使用 NextLine),而不是一次读一个单词(Next)

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

创建一个名为我的对象的类

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);    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 2011-01-13
    相关资源
    最近更新 更多