java获取压缩文件(zip、rar)里的XML并进行解析保存到数据库


屈指可数的日子里,希望你继续坚持下去


实体类(ResourceLib)

import lombok.Data;

@Data
public class ResourceLib {
    private String MC; //名称
    private String TIME;//时间
    private String PRODUCTS_ID;//id
}

实现类

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;  //临时新建XML文件地址

private static String url = "数据库Url路径";
private static String Parent_id = "";//主键ID(根据实际需求可有可无)
/**
 * 获取压缩文件里的XML并进行解析
 * @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完成----");
                    //调用writeToMysql方法保存至数据库
                    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();
                // 递归调取解压
                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();//获取根节点
        System.out.println(root.getName());//打印根节点root
        List<Element> list = root.elements();//所有root下第一子节点存进一个集合中
        //遍历节点
        for (Element e : list) {
            ResourceLib resourceLib = new ResourceLib();//放在循环里面,循环完一个后接着下一个
            System.out.println(e.getName());//获取根结点下第一根子节点
            resourceLib.setTIME(e.elementText("sj"));
            resourceLib.setMC(e.elementText("mc"));
            listnode.add(resourceLib);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return listnode;
}


/**
 * 保存到数据库
 * @param resourceLibs
 */
public static void writeToMysql(List<ResourceLib> resourceLibs) {
    Connection conn = null;
    try {
        // 加载MySql的驱动类
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        System.out.println("找不到驱动程序类 ,加载驱动失败!");
        e.printStackTrace();
    }
    //2.建立连接
    Statement st = null;
    //调用DriverManager对象的getConnection()方法,获得一个Connection对象
    Connection con  =null;
    try {
        //建立数据库连接
        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(); //创建一个Statement对象
            st.executeUpdate(sql);//提交数据更新
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }finally{
        try {
            st.close();
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
         }
     }
  }	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值