All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.founder.sdk.utils.DownLoadZipUtil Maven / Gradle / Ivy

There is a newer version: 3.6.1.9
Show newest version
package com.founder.sdk.utils;

import cn.hutool.core.date.DatePattern;
import com.founder.core.log.MyLog;
import com.founder.sdk.annotation.ReadTxt;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class DownLoadZipUtil {

    private static final MyLog _log = MyLog.getLog(DownLoadZipUtil.class);

    public static  List downloadToList(InputStream buffer, HashMap> map, Class clazz){
        ArrayList array = new ArrayList<>();
        BufferedReader reader = null;
        try {
            ZipArchiveInputStream zipFile = new ZipArchiveInputStream(buffer);
            ZipArchiveEntry nextZipEntry = zipFile.getNextZipEntry();
            if (!nextZipEntry.isDirectory()) {
                _log.info("不是目录就进行解析");
                reader = new BufferedReader(new InputStreamReader(zipFile,"UTF-8"));
                String line;
                while ((line = reader.readLine()) != null) {
                    _log.info("逐行解析(UTF-8):" + line);
                    String[] split = line.split("\\t",-1);
                    if (map.size() != split.length) {
                        _log.warn("提示字段不等(暂时不限制)");
                    }
                    if (split.length < map.size()) {
                        _log.info("问题行,跳过(暂时不限制)");
                        //continue;
                        String[] splittmp = Arrays.copyOf(split,map.size());
                        _log.info("文件分割长度不够,根据表自动扩容");
                        split = splittmp;
                    }
                    //排序与字段的set方法映射
                    try {
                        T instance = clazz.newInstance();
                        for (Integer key : map.keySet()) {
                            List info = map.get(key);
                            setValue(instance, key, split, info);
                        }
                        array.add(instance);
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalStateException("压缩文件解析出错");
        } finally {
            IOUtils.closeQuietly(reader);
        }
        return array;
    }

    private static  void setValue(T instance, int i, String[] s, List info) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ParseException, ClassNotFoundException {
        Integer index = (Integer) info.get(0)-1;
        String name = (String) info.get(1);
        Class aClass = Class.forName((String)info.get(2));
        String desc = (String) info.get(3);
        if (info.get(0) != null) {
            _log.debug("开始填充第"+ i + "个字段:" + name + "(" + desc + ")值为:" + s[index]);
            Method method = instance.getClass().getMethod(name, aClass);
            if(aClass == new Date().getClass()){
                if (StringUtils.isEmpty(s[index]) || "null".equalsIgnoreCase(s[index])){
                    _log.info("日期类型的字段如果是null或者空,不填充");
                } else {
                    try {
                        Date date = DateUtils.parseDate(s[index],new String[]{"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"});
                        method.invoke(instance, date);
                    } catch (ParseException ex) {
                        _log.error(ex, ex.getMessage());
                        SimpleDateFormat df = new SimpleDateFormat(DatePattern.JDK_DATETIME_PATTERN, Locale.ENGLISH);
                        try {
                            Date date = df.parse(s[index]);
                            method.invoke(instance, date);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }else{
                method.invoke(instance, s[index]);
            }
        }
    }

    @Deprecated
    public static  List downloadToList(InputStream buffer, Class clazz){
        ArrayList array = new ArrayList<>();
        BufferedReader reader = null;
        try {
            ZipArchiveInputStream zipFile = new ZipArchiveInputStream(buffer);
            ZipArchiveEntry nextZipEntry = zipFile.getNextZipEntry();
            if (!nextZipEntry.isDirectory()) {
                //不是目录就进行解析
                reader = new BufferedReader(new InputStreamReader(zipFile));
                String line;
                //排序与字段的set方法映射
                HashMap> map = prepareSetMap(clazz);
                while ((line = reader.readLine()) != null) {
                    _log.debug("逐行解析:" + line);
                    String[] split = line.split("\\t",-1);
                    if (map.size() != split.length) {
                        _log.warn("提示字段不等(暂时不限制)");
                    }
                    //存储操作
                    T instance = clazz.newInstance();
                    for (int i = 0; i < split.length; i++) {
                        setValue(instance, i+1, split[i], map);
                    }
                    array.add(instance);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalStateException("压缩文件解析出错");
        } finally {
            IOUtils.closeQuietly(reader);
        }
        return array;
    }

    private static  void setValue(T instance, int i, String s, HashMap> map) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ParseException {
        List info = map.get(i);
        String name = (String) info.get(0);//方法名称
        Class aClass = (Class) info.get(1);
        String desc = (String) info.get(2);
        if (info.get(0) != null) {
            _log.debug("开始填充第"+ i + "个字段:" + name + "(" + desc + ")值为:" + s);
            Method method = instance.getClass().getMethod(name, aClass);
            if(aClass == new Date().getClass()){
                if (StringUtils.isEmpty(s) || "null".equalsIgnoreCase(s)){
                    _log.info("日期类型的字段如果是null或者空,不填充");
                } else {
                    SimpleDateFormat df = new SimpleDateFormat(DatePattern.JDK_DATETIME_PATTERN, Locale.ENGLISH);
                    Date date = df.parse(s);
                    method.invoke(instance, date);
                }
            }else{
                method.invoke(instance, s);
            }
        }
    }

    @Deprecated
    private static  HashMap> prepareSetMap(Class clazz) {
        HashMap> map = new HashMap<>();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            ReadTxt readTxt = field.getAnnotation(ReadTxt.class);
            if (readTxt != null) {
                String name = field.getName();
                ArrayList info = new ArrayList();
                //存储set方法、及参数类型
                info.add("set" + name.substring(0, 1).toUpperCase() + name.substring(1));
                info.add(field.getType());
                info.add(readTxt.name());//字段说明
                map.put(readTxt.order(), info);
            }
        }
        return map;
    }

    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("C:\\Users\\zhunian\\Downloads\\1302.zip");
        FileInputStream buffer = new FileInputStream(file);
        //List list = DownLoadZipUtil.downloadToList(buffer,DownCatalog1302ResponseOutputFileinfoData.class);
        //System.out.println(JSON.toJSONString(list));
    }
}