栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【无标题】111

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【无标题】111

package com.mms.webService.util;

import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.*;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import static javax.swing.UIManager.getString;


public class ZipUtils {
      public static void main(String[] args) throws Exception {
             // 解压文件
            Path file = Paths.get("D:\ALL\Java\MMS.zip"); //绝对路径
            System.out.println("压缩文件:"+file);
            Path targetDir = Paths.get("D:\ALL\Java\");
            System.out.println("解压文件输出的目录:"+targetDir);
            ZipUtils.unPacket(file,targetDir);

             // 压缩指定的文件
//          Path folder1 = Paths.get("C:\Users\hp\Desktop\1.txt");
//          Path folder2 = Paths.get("C:\Users\hp\Desktop\2.txt");
//          Path[] arr = {folder1,folder2};
//          Path zipFile = Paths.get("C:\Users\hp\Desktop\www.zip");
//          ZipUtils.packet(arr,zipFile);

             // 压缩指定的目录
            
      }
      
      public static void unPacket(Path file, Path targetDir) throws IOException {
            System.out.println("解压文件start......");
            if (!Files.exists(targetDir)) {
                  Files.createDirectories(targetDir);
            }
            // 创建zip对象
            ZipFile zipFile = new ZipFile(file.toFile());
            try {
                  // 读取zip流
                  try(ZipInputStream zipInputStream = new ZipInputStream(Files.newInputStream(file))){
                        Charset.forName("GBK");
                        ZipEntry zipEntry = null;
                        // 遍历每一个zip项
                        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                              // 获取zip项目名称
                              String entryName = zipEntry.getName();
                              // 构建绝对路径
                              Path entryFile = targetDir.resolve(entryName);
                              if(zipEntry.isDirectory()) {   // 文件夹
                                    if (!Files.isDirectory(entryFile)) {
                                          Files.createDirectories(entryFile);
                                    }
                              } else {                     // 文件
                                    // 读取zip项数据流
//                                  try(InputStream zipEntryInputStream = zipFile.getInputStream(zipEntry)){
//                                        try(OutputStream fileOutputStream = Files.newOutputStream(entryFile, StandardOpenOption.CREATE_NEW)){
//                                              byte[] buffer = new byte[4096];
//                                              int length = 0;
//                                              while ((length = zipEntryInputStream.read(buffer)) != -1) {
//                                                    fileOutputStream.write(buffer, 0, length);
//                                              }
//                                              fileOutputStream.flush();
//                                        }
//                                  }
                              }
//                         File file1= new File(entryFile.toString());
//                         if (!file1.exists()){
//                            throw new Exception("文件不存在!");
//                         }
//                         InputStream in = new FileInputStream(file1);
                           InputStream in =zipFile.getInputStream(zipEntry);
                           // 读取整个Excel
                           XSSFWorkbook sheets = new XSSFWorkbook(in);
                           // 获取第一个表单Sheet
                           XSSFSheet sheetAt = sheets.getSheetAt(0);
                           ArrayList> list = new ArrayList<>();

                           Map pictures = getPictures(sheetAt);
                           //默认第一行为标题行,i = 0
                           XSSFRow titleRow = sheetAt.getRow(0);
                           // 循环获取每一行数据
                           for (int i = 1; i < sheetAt.getPhysicalNumberOfRows(); i++) {
                              XSSFRow row = sheetAt.getRow(i);
                              LinkedHashMap map = new LinkedHashMap<>();
                              // 读取每一格内容
                              for (int index = 0; index < row.getPhysicalNumberOfCells(); index++) {
                                 XSSFCell titleCell = titleRow.getCell(index);
                                 XSSFCell cell = row.getCell(index);
                                 // cell.setCellType(XSSFCell.CELL_TYPE_STRING); 过期,使用下面替换
                                 cell.setCellType(CellType.STRING);
                                 if (cell.getStringCellValue().equals("")) {
                                    continue;
                                 }
                                 map.put(getString(titleCell), getString(cell));
                              }
                              if (map.isEmpty()) {
                                 continue;
                              }
                              list.add(map);
                           }
                           for (Integer i = 0; i < list.size(); i++) {
                              Map stringObjectMap = list.get(i);
                              if(pictures.get(i+1)!=null){
                                 stringObjectMap.put(i.toString(),pictures.get(i+1).getData());
                                 byte[] data = pictures.get(i+1).getData();

                                 String jpgFileName = "/img_" + UUID.randomUUID().toString().replaceAll("-","")+".jpg";
                                 System.out.println(jpgFileName+":"+data.length);
                                 //图片保存路径
                                 FileOutputStream out = new FileOutputStream("D:\ALL\Java\"+jpgFileName);
                                 out.write(data);
                                 out.close();
                              }

                              stringObjectMap.forEach((key,val)->{
                                 System.out.println(key+":"+val);
                              });
                           }

                        }
                  } catch (Exception e) {
                     e.printStackTrace();
                  }
            } finally {
                  zipFile.close();
                  System.out.println("关闭资源......");
            }

      }

   public static Map getPictures(XSSFSheet xssfSheet){

      Map map=new HashMap<>();
      List list=xssfSheet.getDrawingPatriarch().getShapes();

      for (XSSFShape shape:list){

         XSSFPicture picture = (XSSFPicture) shape;
         XSSFClientAnchor xssfClientAnchor=(XSSFClientAnchor) picture.getAnchor();
         XSSFPictureData pdata = picture.getPictureData();
         // 行号-列号xssfClientAnchor.getRow1() + "-" + xssfClientAnchor.getCol1()
         Integer key = xssfClientAnchor.getRow1();
         map.put(key, pdata);
         System.out.println("key:"+key);
      }
      return map;
   }
   
   public static String getString(XSSFCell xssfCell) {
      if (xssfCell == null) {
         return "";
      }
      if (xssfCell.getCellTypeEnum() == CellType.NUMERIC) {
         return String.valueOf(xssfCell.getNumericCellValue());
      } else if (xssfCell.getCellTypeEnum() == CellType.BOOLEAN) {
         return String.valueOf(xssfCell.getBooleanCellValue());
      } else {
         return xssfCell.getStringCellValue();
      }
   }
      
      public static void packet(Path[] files, Path zipFile) throws IOException {
            OutputStream outputStream = Files.newOutputStream(zipFile, StandardOpenOption.CREATE_NEW);
            ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
            try {
                  for (Path file : files) {
                        if (Files.isDirectory(file)) {
                              continue;
                        }
                        try (InputStream inputStream = Files.newInputStream(file)) {
                              // 创建一个压缩项,指定名称
                              ZipEntry zipEntry = new ZipEntry(file.getFileName().toString());
                              // 添加到压缩流
                              zipOutputStream.putNextEntry(zipEntry);
                              // 写入数据
                              int len = 0;
                              byte[] buffer = new byte[1024 * 10];
                              while ((len = inputStream.read(buffer)) > 0) {
                                    zipOutputStream.write(buffer, 0, len);
                              }
                              zipOutputStream.flush();
                        }
                  }
                  // 完成所有压缩项的添加
                  zipOutputStream.closeEntry();
            } finally {
                  zipOutputStream.close();
                  outputStream.close();
            }
      }

      
      public static void packet(Path folder, Path zipFile) throws IOException {
            if (!Files.isDirectory(folder)) {
                  throw new IllegalArgumentException(folder.toString() + " 不是合法的文件夹");
            }
            OutputStream outputStream = Files.newOutputStream(zipFile, StandardOpenOption.CREATE_NEW);
            ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);

            LinkedList path = new LinkedList<>();

            try {
                  Files.walkFileTree(folder, new FileVisitor() {

                        @Override
                        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {

                              if (!dir.equals(folder)) {
                                    // 开始遍历目录
                                    String folder = dir.getFileName().toString();
                                    path.addLast(folder);
                                    // 写入目录
                                    ZipEntry zipEntry = new ZipEntry(path.stream().collect(Collectors.joining("/", "", "/")));
                                    try {
                                          zipOutputStream.putNextEntry(zipEntry);
                                          zipOutputStream.flush();
                                    } catch (IOException e) {
                                          throw new RuntimeException(e);
                                    }
                              }
                              return FileVisitResult.CONTINUE;
                        }

                        @Override
                        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                              // 开始遍历文件
                              try (InputStream inputStream = Files.newInputStream(file)) {

                                    // 创建一个压缩项,指定名称
                                    String fileName = path.size() > 0
                                                ? path.stream().collect(Collectors.joining("/", "", "")) + "/" + file.getFileName().toString()
                                                : file.getFileName().toString();

                                    ZipEntry zipEntry = new ZipEntry(fileName);

                                    // 添加到压缩流
                                    zipOutputStream.putNextEntry(zipEntry);
                                    // 写入数据
                                    int len = 0;
                                    byte[] buffer = new byte[1024 * 10];
                                    while ((len = inputStream.read(buffer)) > 0) {
                                          zipOutputStream.write(buffer, 0, len);
                                    }

                                    zipOutputStream.flush();
                              } catch (IOException e) {
                                    throw new RuntimeException(e);
                              }
                              return FileVisitResult.CONTINUE;
                        }
                        @Override
                        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                              return FileVisitResult.CONTINUE;
                        }
                        @Override
                        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                              // 结束遍历目录
                              if (!path.isEmpty()) {
                                    path.removeLast();
                              }
                              return FileVisitResult.CONTINUE;
                        }
                  });
                  zipOutputStream.closeEntry();
            } finally {
                  zipOutputStream.close();
                  outputStream.close();
            }
      }
}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1003506.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号