zoukankan      html  css  js  c++  java
  • 文件压缩上传Utils

    文件压缩上传utils

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.nio.charset.Charset;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import org.springframework.web.multipart.MultipartFile;
    
    public class FileZipUtil {
        /**
         * 上传压缩文件到指定目录
         * @param sealPfxFile
         * @param path 路径
         * @return
         * @throws IOException
         */
        public static String upload(File sealPfxFile, String path) throws IOException {
            long startTime=System.currentTimeMillis();
            String fileName = sealPfxFile.getName();
            File file = new File(path);
            try {
                if (!file.exists()) {
                    file.mkdirs();// 创建一个已时间戳命名的文件夹
                }
                // 获取输出流
                OutputStream os = new FileOutputStream(path + fileName);
              //  InputStream is = sealPfxFile.getInputStream();
                InputStream is =new FileInputStream(sealPfxFile);
                
                int temp;
                // 一个一个字节的读取并写入
                while ((temp = is.read()) != (-1)) {
                    os.write(temp);
                }
                os.flush();
                os.close();
                is.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            
            long endTime=System.currentTimeMillis(); //获取结束时间
            
            System.out.println("上传时间: "+(startTime-endTime)+"ms");
            return path + fileName;
        }
        
        /**
         * 解压zip文件到指定的目录
         * @param file 要解压的zip文件全路径
         * @param outputDir 要解压到某个指定的目录下
         * @throws IOException
         */
        public static void unZip(String file, String outputDir) throws IOException {
            long startTime=System.currentTimeMillis();
            ZipFile zipFile = null;
            try {
                Charset gbk = Charset.forName("gbk");
                zipFile = new ZipFile(file, gbk);
                createDirectory(outputDir, null);// 创建输出目录
                Enumeration<?> enums = zipFile.entries();
                while (enums.hasMoreElements()) {
                    ZipEntry entry = (ZipEntry)enums.nextElement();
                    if (entry.isDirectory()) {// 是目录
                        createDirectory(outputDir, entry.getName());// 创建空目录
                    } else {// 是文件
                        File tmpFile = new File(outputDir + "/" + entry.getName());
                        createDirectory(tmpFile.getParent() + "/", null);// 创建输出目录
                        InputStream in = null;
                        OutputStream out = null;
                        try {
                            in = zipFile.getInputStream(entry);;
                            out = new FileOutputStream(tmpFile);
                            int length = 0;
                            byte[] b = new byte[2048];
                            while ((length = in.read(b)) != -1) {
                                out.write(b, 0, length);
                            }
                        } catch (IOException ex) {
                            throw ex;
                        } finally {
                            if (in != null)
                                in.close();
                            if (out != null)
                                out.close();
                        }
                    }
                }
            } catch (IOException e) {
                throw new IOException("解压缩文件出现异常", e);
            } finally {
                try {
                    if (zipFile != null) {
                        zipFile.close();
                    }
                } catch (IOException ex) {
                    throw new IOException("关闭zipFile出现异常", ex);
                }
            }
            long endTime=System.currentTimeMillis();
            System.out.println("解压时间: "+(startTime-endTime)+"ms");
        }
        
        /**
         * 创建文件目录
         * @param outputDir
         * @param subDir
         */
        public static void createDirectory(String outputDir, String subDir) {
            File file = new File(outputDir);
            if (!(subDir == null || subDir.trim().equals(""))) {// 子目录不为空
                file = new File(outputDir + "/" + subDir);
            }
            if (!file.exists()) {
                if (!file.getParentFile().exists())
                    file.getParentFile().mkdirs();
                file.mkdirs();
            }
        }
        
        /**
         * 获取Excel的值 第二行开始
         * @param path
         * @param mapKeys 字段依次读取后保存到map的key,用于返回后来根据key获取相关数据
         * @return
         * @throws IOException
         */
        public static List<Map<String, Object>> getListExcel(String path,String[] mapKeys) throws IOException {
            List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
            String excelName = getFileName(path);// 得到该文件夹下的excel名称;只取了第一个
            path = path + excelName;
            InputStream is = new FileInputStream(path);
          //  excelName.endsWith("xlsx");
            try {
                //XSSFWorkbook workbook = new XSSFWorkbook(is);
                Workbook workbook  = null;
                if(excelName.endsWith("xlsx")){
                    workbook = new XSSFWorkbook(is);
                }else{
                    workbook = new HSSFWorkbook(is);
                }
                Sheet sheet = workbook.getSheetAt(0);
                int rows = sheet.getLastRowNum();// 获取所有行数
                //sheet.getL
             //   String str[] = {"name","sex","cardno","address","img","work","economic"}; //定义返回的key
                String str[] = mapKeys; //定义返回的key
                // 循环EXCEL文件 获取每行的记录处理数据 从第2行开始,头行是注释
                for (int i = 1; i <= rows; i++) {
                    Row row = sheet.getRow(i);// 获取第i行
                    int coloumNum = sheet.getRow(i).getLastCellNum();// 获取第i行的列总数
                    Map<String, Object> map = new HashMap<String, Object>();
                    for (int j = 0; j < coloumNum; j++) {
                        Cell data = row.getCell(j);
                        if (data != null && !"".equals(data.toString()) ) {
                            data.setCellType(Cell.CELL_TYPE_STRING);
                            // sheet.getRow(0).getCell(j)获取该列的头部信息.
                            map.put(str[j].trim(), data);
                        } else {
                            map.put(str[j].trim(), "");
                        }
                    }
                    listmap.add(map);
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                is.close();
            }
            return listmap;
        }
        
        // 获取路径下的所有文件
        public static String getFileName(String path) {
            File f = new File(path);
            if (!f.exists()) {
                return "";
            }
            File fa[] = f.listFiles();
            // for (int i = 0; i < fa.length; i++) {
            // System.out.println(fa[0].getName());
            // }
            return fa[0].getName();
        }
        
        
        public static void copyFile(File fromFile,File toFile) throws IOException{
            FileInputStream ins = new FileInputStream(fromFile);
            FileOutputStream out = new FileOutputStream(toFile);
            byte[] b = new byte[1024];
            int n=0;
            while((n=ins.read(b))!=-1){
                out.write(b, 0, n);
            }
            ins.close();
            out.close();
        }
        
        /**
         * 获取图片类型Zip数据信息
         * @param path
         * @return
         */
        public static List<Map<String, Object>> traverseFolder2(String path) {
            List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
            File file = new File(path);
            if (file.exists()) {
                File[] files = file.listFiles();
                if (null == files || files.length == 0) {
                    System.out.println("文件夹是空的!");
                    return listMap;
                } else {
                    for (File file2 : files) {
                        if (file2.isDirectory()) {
                            System.out.println("文件夹:" + file2.getAbsolutePath());
                            //解决bug,如果是包含excel文件的,说明是模式1,并非 只有图片上传模式(模式2),详情看人员导入方法 TControlinfo.importZip();
                            if(file2.getAbsolutePath().indexOf("excel")>0){ 
                                listMap.clear(); 
                                return listMap;
                            }
                            listMap.addAll(traverseFolder2(file2.getAbsolutePath()));
                        } else {
                            Map<String, Object> dataMap = new HashMap<String,Object>();
                            System.out.println("文件:" + file2.getAbsolutePath());
                            String name = file2.getName();
                            if(name.indexOf("zip")>0)continue;
    //                        System.out.println("文件名:" + name);
                            String control_name = "";
                            String control_cardno = ""; 
                            String contrl_address = "";
                            name = name.substring(0,name.indexOf("."));
                            String[] split = name.split("_");
                            if(split.length == 1){
                                 control_name = split[0];
                            }else if(split.length == 2){
                                control_name = split[0];
                                control_cardno = split[1];
                            }else if(split.length == 3){
                                control_name = split[0];
                                control_cardno = split[1];
                                contrl_address = split[2];
                            }
    //                        
                            dataMap.put("cardno", control_cardno);
                            dataMap.put("name", control_name);
                            dataMap.put("address", contrl_address);
                            dataMap.put("img", file2.getAbsolutePath());
                            listMap.add(dataMap);
                        }
                    }
                }
            } else {
                System.out.println("文件不存在!");
            }
            return listMap;
        }
  • 相关阅读:
    EditText setError 图片不显示问题
    android TextView getlinecount返回0
    PANIC: Could not open AVD config file:
    case expressions must be constant expressions
    无法创建抽象类或接口“Newtonsoft.Json.JsonWriter”的实例
    Listview嵌套ListView 及包含button onItemClic失效问题
    errror initializing phoneGap:class not found
    动态添加ImageView 设置setPadding不起作用问题
    Parameter 参数替换成value
    Listview addHeaderView添加view报错
  • 原文地址:https://www.cnblogs.com/wangquanyi/p/12106880.html
Copyright © 2011-2022 走看看