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