美文网首页java学习之路
java上传zip文件并解析出指定内容

java上传zip文件并解析出指定内容

作者: 唯有努力不欺人丶 | 来源:发表于2023-04-22 17:12 被阅读0次

    背景是有一个上传压缩包,然后解析出指定出包名和版本的需求,直接上代码:
    接口:

        @PostMapping(value = "/upload")
        public Map<String,String> upload(@RequestParam("file") MultipartFile file){
            try {
                File zipFile = new File(FILE_UPLOAD_PATH + file.getOriginalFilename());
                file.transferTo(zipFile);
                return UploadAndUnzipUtils.getContainerName(zipFile.getAbsolutePath());
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    

    工具类:

    package com.lenovo.common.utils;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    
    
    public class UploadAndUnzipUtils {
    
        public static Map<String,String> getContainerName(String zipFilePath) throws IOException {
    
            try {
                ZipFile zipFile = new ZipFile(zipFilePath);
                Enumeration<?> entries = zipFile.entries();
    
                while (entries.hasMoreElements()) {
                    ZipEntry entry = (ZipEntry) entries.nextElement();
                    if (entry.getName().equals("Container.xml")) {
                        Map<String,String> res = new HashMap<>();
                        InputStream inputStream = zipFile.getInputStream(entry);
                        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                        Document document = documentBuilder.parse(inputStream);
                        Element container = document.getDocumentElement();
                        res.put("name",container.getAttribute("name"));
                        res.put("version",container.getAttribute("version"));
                        return res;
                    }
                }
            }catch (Exception e){
    
            }
            return null;
        }
    }
    

    如果稍微帮到你了记得点个喜欢点个关注~

    相关文章

      网友评论

        本文标题:java上传zip文件并解析出指定内容

        本文链接:https://www.haomeiwen.com/subject/nuwsjdtx.html