Apache-Commons CSV读写文件

2018-03-24 01:11:03
1498次阅读
0个评论

读取CSV文件:

import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
 
public class CsvFileReader {
     
    //CSV文件头
    private static final String [] FILE_HEADER = {"用户名","密码","名称","年龄"};
     
    /**
     * @param fileName
     */
    public static void readCsvFile(String fileName) {
        FileReader fileReader = null;
        CSVParser csvFileParser = null;
        //创建CSVFormat(header mapping)
        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER);
        try {
            //初始化FileReader object
            fileReader = new FileReader(fileName);
            //初始化 CSVParser object
            csvFileParser = new CSVParser(fileReader, csvFileFormat);
            //CSV文件records
            List<CSVRecord> csvRecords = csvFileParser.getRecords();
            // CSV
            List<User> userList = new ArrayList<User>();
            //
            for (int i = 1; i < csvRecords.size(); i++) {
                CSVRecord record = csvRecords.get(i);
                //创建用户对象填入数据
                User user = new User(record.get("用户名"), record.get("密码"),
                            record.get("名称"), Integer.parseInt(record.get("年龄")));
                userList.add(user);
            }
            // 遍历打印
            for (User user : userList) {
                System.out.println(user.toString());
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileReader.close();
                csvFileParser.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
     
    /**
     * @param args
     */
    public static void main(String[] args){
        readCsvFile("c://users.csv");
    }
 
}


写入CSV文件:


import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
 
public class CsvFileWriter {
     
    //CSV文件分隔符
    private static final String NEW_LINE_SEPARATOR = "\n";
     
    //CSV文件头
    private static final Object [] FILE_HEADER = {"用户名","密码","名称","年龄"};
     
    /**
     * 写CSV文件
     *
     * @param fileName
     */
    public static void writeCsvFile(String fileName) {
        FileWriter fileWriter = null;
        CSVPrinter csvFilePrinter = null;
        //创建 CSVFormat
        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
        try {
            //初始化FileWriter
            fileWriter = new FileWriter(fileName);
            //初始化 CSVPrinter
            csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
            //创建CSV文件头
            csvFilePrinter.printRecord(FILE_HEADER);
 
            // 用户对象放入List
            List<User> userList = new ArrayList<User> ();
            userList.add(new User("zhangsan", "123456", "张三", 25));
            userList.add(new User("lisi", "123", "李四", 23));
            userList.add(new User("wangwu", "456", "王五", 24));
            userList.add(new User("zhaoliu", "zhaoliu", "赵六", 20));
             
            // 遍历List写入CSV
            for (User user : userList) {
                List<String> userDataRecord = new ArrayList<String>();
                userDataRecord.add(user.getUsername());
                userDataRecord.add(user.getPassword());
                userDataRecord.add(user.getName());
                userDataRecord.add(String.valueOf(user.getAge()));
                csvFilePrinter.printRecord(userDataRecord);
            }
            System.out.println("CSV文件创建成功~~~");
             
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileWriter.flush();
                fileWriter.close();
                csvFilePrinter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
     
    /**
     * @param args
     */
    public static void main(String[] args){
        writeCsvFile("c://users.csv");
    }
     
}




收藏00

登录 后评论。没有帐号? 注册 一个。