`
chengyu2099
  • 浏览: 459815 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

CSVReader

 
阅读更多
package com.zte.nva.dap.hadoop.csvreader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
/**
 * 
 * @author 
 * @version v1.0
 * @msg.get csv list 
 * @csv API : http://opencsv.sourceforge.net/apidocs/index.html
 */
public class CsvReaderTest 
{
 public static void main(String[] args)throws Exception 
 {
  String file = "f:"+File.separator+"test.csv";
  /**
   * 测试写一个csv文件
   */
//  new CsvReaderTest().writeCSV(file);
  /**
   * 读取指定列的csv文件 
   */
//  new CsvReaderTest().getCSVList1(file);
 }
 /**
  * @param file,file demo adress 
  * @return list
  * @description get all col cell value to add list
  */
 private List<String> getCSVList1(String file)
 {
  //取特定列放到集合
  List<String> list = new ArrayList<String>();
  //取特定列放到数组
  String[] csvArray ;
  CSVReader reader = null;
  try {
   /*
    * 获取所有列集合信息
    * CSVReader reader = new CSVReader(new FileReader(file),'\t', '\''); */
   reader = new CSVReader(new FileReader(file));
   String [] nextLine;
   System.out.println("一共有: " + reader.readNext().length+" 列");
   StringBuffer sb = new StringBuffer();
   while ((nextLine = reader.readNext()) != null) 
   {
    //获取指定列的集合信息,放到集合中
    list.add(nextLine[0]);
    //取特定列放到数组
    sb.append(nextLine[0]);
    sb.append(",");
   }
   //遍历集合
   for(String str1 : list){
    System.out.println("value : " + str1);
   }
   System.out.println("***********************************************");
   //遍历数组
   csvArray = sb.toString().split(",");
   for(String str2 : csvArray){
    System.out.println("value : " + str2);
   }
   
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  finally {
   if(reader != null){
    try {
     reader.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
     return list;
 }
 /**
  * 生成一个大数据量的csv测试文件
  */
 public void writeCSV(String file){
  try 
  {
   CSVWriter writer = new CSVWriter(new FileWriter(file), '\t');
   long startTime=System.currentTimeMillis();   //获取开始时间 
   for(int i=0;i<100000;i++)
   {
    writer.writeNext(new String[]{String.valueOf(i)});
   }
   long endTime=System.currentTimeMillis(); //获取结束时间
   System.out.println("程序运行时间: "+(endTime-startTime)+"毫秒");   
   writer.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

}
分享到:
评论
1 楼 kingdelee 2013-05-10  
请问博主,怎么解决中文乱码问题,谢谢~~~

相关推荐

Global site tag (gtag.js) - Google Analytics