Mousika

天地孤影任我行

导航

openCSV操作CSV文件实例

opencsv.jar下载地址:http://download.csdn.net/detail/lujian863/4604588

1.读取CSV文件

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

import au.com.bytecode.opencsv.CSVReader;

//读取CSV文件
public class MyCSVReader {
    private String path;
    public MyCSVReader(String path){
        this.path = path;
    }
    
    public List<String[]> getCSVContent(){
        List<String[]> fcontent = null;
        try {
            File f = new File(path);
            CSVReader cr = new CSVReader(new FileReader(f));
            fcontent  = cr.readAll();
        } catch (FileNotFoundException e) {
            System.out.println("CSV文件未找到!");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("CSV文件读取出错!");
            e.printStackTrace();
        }
        return fcontent;
    }
    
}

2.写入CSV文件

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import au.com.bytecode.opencsv.CSVWriter;

public class MyFileWriter {
    
    public static void writeCVS(String[][] sc, String fname) throws IOException {
        File tempFile = new File(fname);
        CSVWriter writer = new CSVWriter(new FileWriter(tempFile));
        for (int i = 0; i < sc.length; i++) {
            writer.writeNext(sc[i]);
        }
        writer.close();
    }
    
    public static void writeCVSWithMap(Map<Integer, ArrayList<Integer>>  ma,String fname) throws IOException{
        File tempFile = new File(fname);
        CSVWriter writer = new CSVWriter(new FileWriter(tempFile));
        Set<Integer> key = ma.keySet();
        for (Iterator<Integer> it = key.iterator(); it.hasNext();) {
            int i = it.next();
            String[] tmp = new String[ma.get(i).size()];
            for(int j = 0; j < ma.get(i).size(); j++){
                tmp[j] = Integer.toString(ma.get(i).get(j));
            }
            writer.writeNext(tmp);
        }

        writer.close();
    }
}

posted on 2012-09-28 01:12  lujian863  阅读(2502)  评论(0编辑  收藏  举报