CSV文件读写操作

CSV文件读写操作

CSVOperationUtil

import com.alibaba.fastjson.JSON;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.CSVWriter;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
import com.opencsv.exceptions.CsvValidationException;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Author zhaozhen
 * @Date 2021/8/9 8:42 下午
 * @Version 1.0
 */
public class CSVOperationUtil {
    /**
     * 使用Javabean来读取文件
     * @param filePath
     * @param clazz
     * @param <T>
     * @return
     * @throws FileNotFoundException
     */
    public static <T> List<T> readToBean(String filePath,Class<T> clazz) throws FileNotFoundException {
        Reader reader = new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8);
        CSVReader csvReader = new CSVReaderBuilder(reader).build();
        CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(csvReader)
                .withSeparator(CSVWriter.DEFAULT_SEPARATOR)
                .withQuoteChar(CSVWriter.NO_QUOTE_CHARACTER)
                .withType(clazz)
                .build();
        List<T> list = csvToBean.parse( );
        return list;
    }

    /**
     * 从filePath中读出内容,按行读,返回List<String[]>
     *
     * @param filePath
     * @return
     * @throws IOException
     * @throws CsvValidationException
     */
    public static List<String[]> readerByLine(String filePath) throws IOException, CsvValidationException {
        CSVReader reader = new CSVReader(new FileReader(filePath));
        String[] nextLine;
        List<String[]> tmpList = new ArrayList<>();
        while ((nextLine = reader.readNext()) != null) {
            tmpList.add(nextLine);
        }
        return tmpList;
    }

    /**
     * 一次全部读出,返回List<String[]>
     * @param filePath
     * @return
     * @throws IOException
     * @throws CsvValidationException
     */
    public static List<String[]> readerByAll(String filePath) throws IOException, CsvException {
        CSVReader reader = new CSVReader(new FileReader(filePath));
        List<String[]> tmpList = reader.readAll();
        return tmpList;
    }


    /**
     * csv写入
     * @param filePath
     * @param list
     * @param <T>
     */
    public static<T> void writeToFile(String filePath,List<T> list) throws CsvRequiredFieldEmptyException, CsvDataTypeMismatchException, IOException {
        Writer writer = new FileWriter(filePath);
        CSVWriter csvWriter = new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER, '\\', "\n");
        StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
                .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
                .withSeparator(CSVWriter.DEFAULT_SEPARATOR)
                .withEscapechar('\\')
                .build();
        beanToCsv.write(list);
        csvWriter.close();
        writer.close();
    }

    public static <T> void writeToFileByStrings (String filePath, List<T> List) throws IOException {
        Writer writer = new FileWriter(filePath);
        CSVWriter csvWriter = new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR,
                CSVWriter.NO_QUOTE_CHARACTER, '\\', "\n");
		
		//将Javabean转换为string[],然后按行写入
        //    for (LinkID linkID : linkIDList) {
        //        csvWriter.writeNext(new String[]{linkID.getMtl_id(), linkID.getMesh(), linkID.getRoad_id(), linkID.getDb_road_id()});
        //    }
                //csvWriter.close();
    }

    /**
     * 将任意类型转换成字符串
     * @param value
     * @param <T>
     * @return
     */
    public static <T> String beanToString(T value) {
        Class<?> clazz = value.getClass();
        if(clazz == int.class || clazz == Integer.class) {
            return value + "";
        }else if(clazz == String.class) {
            return (String)value;
        }else if(clazz == long.class || clazz == Long.class) {
            return value + "";
        }else {
            return JSON.toJSONString(value);
        }
    }



    public static void main(String[] args) throws IOException, CsvRequiredFieldEmptyException, CsvDataTypeMismatchException {
        List<LinkID> linkIDList;
        linkIDList = readToBean("/Users/zhaozhen/Work/document/excel/tmp_link_id.csv",LinkID.class);
        String csvFilePath = "/Users/zhaozhen/Work/document/excel/testWrite.csv";
        writeToFile(csvFilePath,linkIDList);
      
    }
}

LinkID


/**
 * @Author zhaozhen
 * @Date 2021/8/9 8:55 下午
 * @Version 1.0
 */
@Data
public class LinkID {
    @CsvBindByPosition(position = 0)
    String mtl_id;
    @CsvBindByPosition(position = 1)
    String mesh;
    @CsvBindByPosition(position = 2)
    String road_id;
    @CsvBindByPosition(position = 3)
    String db_road_id;


    @Override
    public boolean equals(Object object){
        boolean meshFlag =false;
        boolean dbRoadIdFlag = false;
        boolean roadFlag =false;

        if(object instanceof LinkID){
            LinkID linkID = (LinkID) object;
            if(this.mtl_id.equals(linkID.mtl_id)){
                if((this.mesh == null && linkID.mesh == null)||(this.mesh == null && linkID.mesh != null) ||(linkID.mesh == null && this.mesh != null) || this.mesh.equals(linkID.mesh)){
                    meshFlag = true;
                }
                if((this.road_id == null && linkID.road_id == null)||(this.road_id == null && linkID.road_id != null) ||(linkID.road_id == null && this.road_id != null)|| this.road_id.equals(linkID.road_id)){
                    roadFlag = true;
                }

                if((this.db_road_id == null && linkID.db_road_id == null)||(this.db_road_id == null && linkID.db_road_id != null) ||(linkID.db_road_id == null && this.db_road_id != null) || this.db_road_id.equals(linkID.db_road_id)){
                    dbRoadIdFlag = true;
                }
                }
        }

        if(meshFlag&&dbRoadIdFlag&&roadFlag){
            return true;
        }
        return false;
    }

    @Override
    public int hashCode() {
        int hash=mtl_id.hashCode();
        if(mesh != null){
            hash+= mesh.hashCode();
        }
        if(road_id != null){
            hash+=road_id.hashCode();
        }
        if(db_road_id != null){
            hash+=db_road_id.hashCode();
        }
        return hash;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值