java获取压缩文件中的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 rBIYHgevUParent_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); } www.devze.com 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<>(); tjsry { 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.clhttp://www.devze.comose(); } catch (SQLException e) { e.printStackTrace(); } } } }
方法补充
下面小编为大家整理了Java读取zip压缩包下xml文件的相关方法,有需要的可以参考一下
方法一:
1.主方法入口
这里省略controller层直接进来,读取端上传的文件,添加非空判断。inputStream流通过自定义工具类的转换方法转成file文件,再将其转为ZipFile进行循环读取。
/** * 读取传入的xml */ public Result readXml(MultipartFile multipartFile) throws Exception { // 判断是否有文件 if (multipartFile == null || multipartFile.isEmpty()) { return Result.failed("请选择要导入的文件"); } 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<>(); // 循环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 BupythonfferedReader(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(); } } }
到此这篇关于java获取压缩文件中的XML并解析保存到数据库的文章就介绍到这了,更多相关java xml获取与解析内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!
精彩评论