滴水穿石--Java 操作CSV文件

使用Opencsv操作CSV文件
本文介绍如何使用Opencsv库进行CSV文件的基本读写操作,并提供了将SQL查询结果直接写入CSV文件的方法。

csv文件操作库opencsv.jar下载地址:http://sourceforge.net/projects/opencsv/

1、基本的文件读写

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.List;

import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;

public class CSVUtils {

 /**
  * 将数据写入csv文件
  * @param data 待写入的数据
  * @throws Exception 抛出异常
  */
 public static void writeToCSV(String[][] data) throws Exception{
        File file = new File("test.csv");
        CSVWriter writer = new CSVWriter(new FileWriter(file));
        for (int i = 0; i < data.length; i++) {
            writer.writeNext(data[i]);
        }
        writer.close();
 }
 
 /**
  * 读取csv文件的内容
  * @param fileName
  * @throws Exception
  */
 public static void readFromCSV(String fileName) throws Exception {
  CSVReader reader = new CSVReader(new FileReader("test.csv"));
     /*String [] nextLine;
     while ((nextLine = reader.readNext()) != null) {
         // nextLine[] is an array of values from the line
         System.out.println(nextLine[0] + nextLine[1] + nextLine[2]);
     }*/
  
  List<String[]> myEntries = reader.readAll();//读取所有的内容
  for(int i=0; i<myEntries.size(); i++) { //迭代输出
   String[] temp = myEntries.get(i);
   for(int j=0; j<temp.length; j++)
    System.out.print(temp[j]+'\t');
   System.out.println();
  }
        reader.close();

 }
 
 public static void main(String[] args) { //测试
  String[] header = new String[]{"name", "sex", "age"};
        String[][] data = new String[][]{header, {"Lucy", "F", "22"}, {"Tom", "M", "25"}, {"Lily", "F", "19"}};
        try {
   CSVUtils.writeToCSV(data);
   CSVUtils.readFromCSV("test.csv");
  } catch (Exception e) {
   e.printStackTrace();
  }
  
 }
}

2、可以将sql查询出来的ResultSet直接写入csv文件

public static void queryOnConsole(String account, String sql){
  Connection conn = null;
  Statement stmt = null;
  ResultSet rs = null;
  File tempFile = null;
  try{
   conn = DBUtil.getConn();
   stmt = conn.createStatement();
   rs = stmt.executeQuery(sql);
   tempFile = new File(account+new Date().getTime()+".csv");
         CSVWriter writer = new CSVWriter(new FileWriter(tempFile));
         writer.writeAll(rs, true);
         writer.close();
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   try {
    DBUtil.close(rs, stmt, conn);
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
 }

 

转载于:https://www.cnblogs.com/nexiyi/archive/2012/12/07/2808149.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值