Java 导入zip,并进行解压

场景一:上传zip包,后台进行解压,提取里面的文件,进行上传。

    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.flush();
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @ResponseBody
    @RequestMapping(value = "updPlScpjcjd", method = RequestMethod.POST)
    public ReturnT updPlScpjcjd(KtbgPage page
            , @RequestParam(value = "file", required = false) MultipartFile file
            , @AuthenticationPrincipal UserManagerEntity user
            , HttpServletRequest request, HttpServletResponse response
    ) throws Exception {
        Map map = new HashMap();
        ReturnT re = new ReturnT(map);
        String webSocketUrl = "/updPlScpjcjd-" + page.getP_pycc();
        File zipFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            try {
                ins = file.getInputStream();
                zipFile = new File(file.getOriginalFilename());
                inputStreamToFile(ins, zipFile);
                ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
                int ypxhrs = 0;
                for (Enumeration enumeration = zip.entries(); enumeration.hasMoreElements(); ) {
                    ZipEntry entry = (ZipEntry) enumeration.nextElement();
                    ypxhrs++;
                    // 创建一个数值格式化对象
                    NumberFormat numberFormat = NumberFormat.getInstance();
                    // 设置精确到小数点后2位
                    numberFormat.setMaximumFractionDigits(2);
                    String result = numberFormat.format((float) ypxhrs / (float) zip.size() * 100);
                    messagingTemplate.convertAndSendToUser(user.getId(), webSocketUrl, result); //用户id,路径,消息
                    if (entry.isDirectory()) {
                        continue;
                    }
                    //文件的
                    String filename = entry.getName();
                    System.out.println(filename);
                    int lastIndex = filename.lastIndexOf(".");
                    System.out.println(lastIndex);
                    String xh = filename.substring(0, lastIndex);
                    System.out.println(xh);
                    //将zipEntry转成输入流
                    InputStream inputStream = zip.getInputStream(entry);
                    //将inputstream转换成mulipartFile
                    MultipartFile multipartFile = new MockMultipartFile(filename, filename, "text/plain", inputStream);
                    //文件名就是学号
                    page.setP_xh(xh);
                    //调用上传接口
                    ktbgService.updPlScpjcjd(request, response, page, multipartFile, map);
                }
            } catch (IOException e) {
                e.printStackTrace();
                re.setCode(500);
            } finally {
                if (ins != null) {
                    ins.close();
                }
            }
        }
        return re;
    }

场景二:上传zip,后台进行解压,提取zip包中“文件夹”以及该“文件夹”下的文件后,再进行压缩上传。

    public static void putNextEntry(InputStream inputStream,String name,ZipOutputStream zipOut) throws IOException {
        //读取相关的文件
        InputStream input = inputStream;//
        zipOut.putNextEntry(new ZipEntry(name));
        // 设置注释
        //zipOut.setComment("hello");
        int temp = 0;
        //读取相关的文件
        while((temp = input.read()) != -1){
            //写入输出流中
            zipOut.write(temp);
        }
        //关闭流
        input.close();
    }
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.flush();
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @ResponseBody
    @RequestMapping(value = "updateScPybByNkd", method = RequestMethod.POST)
    public ReturnT updateScPybByNkd(LwdbPage page
            , @RequestParam(value = "file", required = false) MultipartFile file
            , @AuthenticationPrincipal UserManagerEntity user
            , HttpServletRequest request, HttpServletResponse response
    ) throws Exception {
        Map map = new HashMap();
        ReturnT re = new ReturnT(map);
        String webSocketUrl = "/updPlScpjcjd-" + page.getP_pycc();
        File zipFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            try {
                ins = file.getInputStream();
                zipFile = new File(file.getOriginalFilename());
                inputStreamToFile(ins, zipFile);
                ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
                int ypxhrs = 0;
                for (Enumeration enumeration = zip.entries(); enumeration.hasMoreElements(); ) {
                    ZipEntry entry = (ZipEntry) enumeration.nextElement();
                    ypxhrs++;
                    // 创建一个数值格式化对象
                    NumberFormat numberFormat = NumberFormat.getInstance();
                    // 设置精确到小数点后2位
                    numberFormat.setMaximumFractionDigits(2);
                    String result = numberFormat.format((float) ypxhrs / (float) zip.size() * 100);
                    messagingTemplate.convertAndSendToUser(user.getId(), webSocketUrl, result); //用户id,路径,消息
                    if (entry.isDirectory()) {
                        String directoryName = entry.getName();
                        //设置输出流
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        ZipOutputStream zipOut = new ZipOutputStream(out);
                        for (Enumeration enumeration2 = zip.entries(); enumeration2.hasMoreElements(); ) {
                            ZipEntry entry2 = (ZipEntry) enumeration2.nextElement();
                            String fileName = entry2.getName();
                            if (!entry2.isDirectory() && fileName.contains(directoryName)) {
                                //將文件添加到包中
                                putNextEntry(zip.getInputStream(entry2),fileName,zipOut);
                            }
                        }
                        zipOut.close();
                        String fileName = directoryName.replaceAll("/","")+".zip";
                        MultipartFile multipartFile = new MockMultipartFile( fileName, fileName, "text/plain", new ByteArrayInputStream(out.toByteArray()));

                        //解析學號
                        int lastIndex = directoryName.lastIndexOf("_");
                        String xh = directoryName.substring(lastIndex+1, directoryName.length());
                        //文件名就是学号
                        page.setP_xh(xh.replaceAll("/",""));
                        //调用上传接口
                        lwdbService.updPyjlcjfjidByXh(request, response,multipartFile, page);
                        continue;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                re.setCode(500);
            } finally {
                if (ins != null) {
                    ins.close();
                }
            }
        }
        return re;
    }

你可能感兴趣的:(Java,Spring2.0,Java上传zip)