欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java獲取壓縮文件中的XML并解析保存到數(shù)據(jù)庫

 更新時(shí)間:2025年06月11日 10:21:41   作者:cccl.  
這篇文章主要為大家詳細(xì)介紹了如何使用java實(shí)現(xiàn)獲取壓縮文件中的XML并解析保存到數(shù)據(jù)庫,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

實(shí)體類(ResourceLib)

import lombok.Data;

@Data
public class ResourceLib {
    private String MC; //名稱
    private String TIME;//時(shí)間
    private String PRODUCTS_ID;//id
}

實(shí)現(xiàn)類

package com.idea.satresoure.util;

import com.idea.satresoure.vo.ResourceLib;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;
import java.nio.charset.Charset;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;



public class ReadXMLFromZIP {

@Value("${FileXml_Path}")
private static String FileXml_Path;  //臨時(shí)新建XML文件地址

private static String url = "數(shù)據(jù)庫Url路徑";
private static String Parent_id = "";//主鍵ID(根據(jù)實(shí)際需求可有可無)
/**
 * 獲取壓縮文件里的XML并進(jìn)行解析
 * @param file
 * @throws Exception
 */
public static void readZipFile(String file,String Parentid) throws Exception {
    Parent_id = Parentid;
    readZipFile(new File(file));
}
public static void readZipFile(File file) throws Exception {
    ZipFile zf = new ZipFile(file, Charset.forName("GBK"));
    InputStream in = new BufferedInputStream(new FileInputStream(file));
    ZipInputStream zis = new ZipInputStream(in);
    ZipEntry ze;
    while ((ze = zis.getNextEntry()) != null) {
        if (ze.isDirectory()) {
        }else {
            if (ze.getName().endsWith(".xml")) {
                // 不解壓直接讀取size為-1
                if (ze.getSize() == -1) {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    while (true) {
                        int bytes = zis.read();
                        if (bytes == -1) {
                            break;
                        }
                        baos.write(bytes);
                    }
                    baos.close();
                } else {
                    // ZipEntry的size正常
                    byte[] bytes = new byte[(int) ze.getSize()];
                    zis.read(bytes, 0, (int) ze.getSize());
                    //新建xml
                    File file1 = new File(FileXml_Path);
                    PrintWriter pw = new PrintWriter(file1);
                    pw.println(new String(bytes));
                    pw.close();
                    System.out.println("開始解析xml----");
                    List<ResourceLib> listnode = getXml(FileXml_Path);
                    if (file1.exists()){
                        file1.delete();
                    }
                    System.out.println("解析xml完成----");
                    //調(diào)用writeToMysql方法保存至數(shù)據(jù)庫
                    writeToMysql(listnode);
                }
            } else if (ze.getName().endsWith("zip")) {
                //判斷是否為壓縮包,若是則將其解壓出再讀取
                String fileName = file.getName().substring(0, file.getName().lastIndexOf("."));
                File temp = new File(file.getParent() + File.separator + fileName + File.separator + ze.getName());
                if (!temp.getParentFile().exists()) {
                    temp.getParentFile().mkdirs();
                }
                OutputStream os = new FileOutputStream(temp);
                //通過ZipFile的getInputStream方法拿到具體的ZipEntry的輸入流
                InputStream is = zf.getInputStream(ze);
                int len;
                while ((len = is.read()) != -1) {
                    os.write(len);
                }
                os.close();
                is.close();
                // 遞歸調(diào)取解壓
                readZipFile(temp.getPath(),Parent_id);
            }
        }
    }
    zis.closeEntry();
    zis.close();
    zf.close();
}


/**
 * 解析XML
 * @param filePath
 * @return
 * @throws IOException
 */
private static List<ResourceLib> getXml(String filePath) throws IOException {
    //解析
    SAXReader reader = new SAXReader();
    List<ResourceLib> listnode = new ArrayList<>();
    try {
        Document doc = reader.read(filePath);
        Element root=doc.getRootElement();//獲取根節(jié)點(diǎn)
        System.out.println(root.getName());//打印根節(jié)點(diǎn)root
        List<Element> list = root.elements();//所有root下第一子節(jié)點(diǎn)存進(jìn)一個(gè)集合中
        //遍歷節(jié)點(diǎn)
        for (Element e : list) {
            ResourceLib resourceLib = new ResourceLib();//放在循環(huán)里面,循環(huán)完一個(gè)后接著下一個(gè)
            System.out.println(e.getName());//獲取根結(jié)點(diǎn)下第一根子節(jié)點(diǎn)
            resourceLib.setTIME(e.elementText("sj"));
            resourceLib.setMC(e.elementText("mc"));
            listnode.add(resourceLib);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return listnode;
}


/**
 * 保存到數(shù)據(jù)庫
 * @param resourceLibs
 */
public static void writeToMysql(List<ResourceLib> resourceLibs) {
    Connection conn = null;
    try {
        // 加載MySql的驅(qū)動(dòng)類
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        System.out.println("找不到驅(qū)動(dòng)程序類 ,加載驅(qū)動(dòng)失敗!");
        e.printStackTrace();
    }
    //2.建立連接
    Statement st = null;
    //調(diào)用DriverManager對(duì)象的getConnection()方法,獲得一個(gè)Connection對(duì)象
    Connection con  =null;
    try {
        //建立數(shù)據(jù)庫連接
        con = DriverManager.getConnection(url, "root", "123456");
        for (int i=0;i<resourceLibs.size();i++){
            String Parentid = Parent_id;
            String SJ= resourceLibs.get(i).getTIME();
            String MC = resourceLibs.get(i).getMBMC();
            //插入語句格式;
            String sql = "insert into resourcelib(sj,Parentid,mc) values(\""+SJ+"\",\""+Parentid+"\",\""+MC+"\")";
            System.out.println(sql);
            st =  con.createStatement(); //創(chuàng)建一個(gè)Statement對(duì)象
            st.executeUpdate(sql);//提交數(shù)據(jù)更新
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }finally{
        try {
            st.close();
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
         }
     }
  }	
}

方法補(bǔ)充

下面小編為大家整理了Java讀取zip壓縮包下xml文件的相關(guān)方法,有需要的可以參考一下

方法一:

1.主方法入口

這里省略controller層直接進(jìn)來,讀取端上傳的文件,添加非空判斷。inputStream流通過自定義工具類的轉(zhuǎn)換方法轉(zhuǎn)成file文件,再將其轉(zhuǎn)為ZipFile進(jìn)行循環(huán)讀取。

/**
 * 讀取傳入的xml
 */
public Result readXml(MultipartFile multipartFile) throws Exception {
    // 判斷是否有文件
    if (multipartFile == null || multipartFile.isEmpty()) {
        return Result.failed("請(qǐng)選擇要導(dǎo)入的文件");
    }
    File zipFile = new File(multipartFile.getOriginalFilename());
    // 將zip文件夾中文件通過inputStream形式存入zipFile
    FileUtil.inputStreamToFile(multipartFile.getInputStream(), zipFile);
    HashMap<String, JSONObject> map = readZipFile(zipFile);
    zipFile.delete();
    return Result.success(readXmlRespVO);
}

2.自定義工具類

import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
 * @author yhl
 * @date 2023/7/19 17:49
 */
@Slf4j
public class FileUtil {

    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) {
            log.error(" FileUtil下 --> inputStreamToFile() 異常 {}",e);
        }
    }
}

3.主體解析方法

public HashMap<String, JSONObject> readZipFile(File file) throws Exception {
        ZipFile zip = new ZipFile(file, Charset.forName("GBK"));
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        ZipInputStream zis = new ZipInputStream(in);
        HashMap<String, JSONObject> map = new HashMap<>();
        // 循環(huán)zip包下的文件,只讀取后綴是xml格式的
        for (Enumeration enumeration = zip.entries(); enumeration.hasMoreElements(); ) {
            ZipEntry ze = (ZipEntry) enumeration.nextElement();
            if (ze.getName().endsWith(".xml") && ze.getSize() > 0) {
                log.info("file - " + ze.getName() + " : " + ze.getSize() + " bytes");
                BufferedReader br = new BufferedReader(new InputStreamReader(zip.getInputStream(ze), StandardCharsets.UTF_8));
                // 解析讀取xml
                StringBuffer reqXmlData = new StringBuffer();
                String s;
                while ((s = br.readLine()) != null) {
                    reqXmlData.append(s);
                }
                br.close();
                JSONObject jsonObject = XML.toJSONObject(reqXmlData.toString());
                map.put(ze.getName(), jsonObject);
                log.info("JSONObject {}", JacksonUtil.toJsonString(jsonObject));
            }
        }
        zis.closeEntry();
        zis.close();
        zip.close();
        return map;
    }

方法二:

完整代碼

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class ZipXmlReader {
    public static void main(String[] args) {
        String zipFilePath = "path/to/your/zip/file.zip";
        try {
            ZipFile zipFile = new ZipFile(zipFilePath);
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                if (!entry.isDirectory() && entry.getName().endsWith(".xml")) {
                    InputStream inputStream = zipFile.getInputStream(entry);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    String line;
                    StringBuilder xmlContent = new StringBuilder();
                    while ((line = reader.readLine()) != null) {
                        xmlContent.append(line);
                    }
                    reader.close();
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document document = builder.parse(new InputSource(new StringReader(xmlContent.toString())));
                    // 處理解析后的xml文件
                    // ...
                }
            }
            zipFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

到此這篇關(guān)于java獲取壓縮文件中的XML并解析保存到數(shù)據(jù)庫的文章就介紹到這了,更多相關(guān)java xml獲取與解析內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringCloud Config統(tǒng)一配置中心問題分析解決與客戶端動(dòng)態(tài)刷新實(shí)現(xiàn)

    SpringCloud Config統(tǒng)一配置中心問題分析解決與客戶端動(dòng)態(tài)刷新實(shí)現(xiàn)

    springcloud config是一個(gè)解決分布式系統(tǒng)的配置管理方案。它包含了 client和server兩個(gè)部分,server端提供配置文件的存儲(chǔ)、以接口的形式將配置文件的內(nèi)容提供出去,client端通過接口獲取數(shù)據(jù)、并依據(jù)此數(shù)據(jù)初始化自己的應(yīng)用
    2022-10-10
  • Spring?AOP概念及原理解析

    Spring?AOP概念及原理解析

    這篇文章主要介紹了Spring?AOP概念及原理?,通過使用?Spring?AOP?實(shí)現(xiàn)日志管理,我們可以將日志記錄的邏輯從業(yè)務(wù)邏輯中分離出來,簡化了代碼的維護(hù),需要的朋友可以參考下
    2024-07-07
  • Java java.lang.InstantiationException異常案例詳解

    Java java.lang.InstantiationException異常案例詳解

    這篇文章主要介紹了Java java.lang.InstantiationException異常案例詳解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • Netty事件循環(huán)主邏輯NioEventLoop的run方法分析

    Netty事件循環(huán)主邏輯NioEventLoop的run方法分析

    這篇文章主要介紹了Netty事件循環(huán)主邏輯NioEventLoop的run方法分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-03-03
  • SpringBoot解析yml全流程詳解

    SpringBoot解析yml全流程詳解

    本文主要介紹了SpringBoot解析yml全流程詳解,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • springboot連接sqllite遇到的坑及解決

    springboot連接sqllite遇到的坑及解決

    這篇文章主要介紹了springboot連接sqllite遇到的坑及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • Java instanceof用法詳解及實(shí)例代碼

    Java instanceof用法詳解及實(shí)例代碼

    這篇文章主要介紹了Java instanceof用法詳解及實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下
    2017-02-02
  • Java 發(fā)送http請(qǐng)求(get、post)的示例

    Java 發(fā)送http請(qǐng)求(get、post)的示例

    這篇文章主要介紹了Java 發(fā)送http請(qǐng)求的示例,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下
    2020-10-10
  • Spring?Boot項(xiàng)目如何使用Maven打包并帶上依賴

    Spring?Boot項(xiàng)目如何使用Maven打包并帶上依賴

    在這篇博客中,介紹如何使用Maven將Spring?Boot項(xiàng)目及其依賴項(xiàng)打包成一個(gè)可執(zhí)行的jar文件。我們將使用Spring?Boot的spring-boot-maven-plugin插件來完成這個(gè)任務(wù),感興趣的朋友跟隨小編一起看看吧
    2023-06-06
  • idea2023.3安裝及配置詳細(xì)圖文教程

    idea2023.3安裝及配置詳細(xì)圖文教程

    IDEA全稱IntelliJ?IDEA,是Java語言對(duì)的集成開發(fā)環(huán)境,IDEA在業(yè)界被認(rèn)為是公認(rèn)最好的Java開發(fā)工具,這篇文章主要給大家介紹了關(guān)于idea2023.3安裝及配置的相關(guān)資料,需要的朋友可以參考下
    2023-11-11

最新評(píng)論