java獲取壓縮文件中的XML并解析保存到數(shù)據(jù)庫
實(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ū)動類
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("找不到驅(qū)動程序類 ,加載驅(qū)動失敗!");
e.printStackTrace();
}
//2.建立連接
Statement st = null;
//調(diào)用DriverManager對象的getConnection()方法,獲得一個(gè)Connection對象
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對象
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("請選擇要導(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringCloud Feign配置應(yīng)用詳細(xì)介紹
這篇文章主要介紹了SpringCloud Feign配置應(yīng)用,feign是netflix提供的服務(wù)間基于http的rpc調(diào)用框架,在spring cloud得到廣泛應(yīng)用2022-09-09
Spring Core動態(tài)代理的實(shí)現(xiàn)代碼
通過JDK的Proxy方式或者CGLIB方式生成代理對象的時(shí)候,相關(guān)的攔截器已經(jīng)配置到代理對象中去了,接下來通過本文給大家介紹Spring Core動態(tài)代理的相關(guān)知識,需要的朋友可以參考下2021-10-10
Spring Security OAuth2實(shí)現(xiàn)使用JWT的示例代碼
這篇文章主要介紹了Spring Security OAuth2實(shí)現(xiàn)使用JWT的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-09-09
java設(shè)計(jì)模式之外觀模式(Facade)
這篇文章主要為大家詳細(xì)介紹了java設(shè)計(jì)模式之外觀模式Facade的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01
如何在Springboot實(shí)現(xiàn)攔截器功能
其實(shí)spring boot攔截器的配置方式和springMVC差不多,只有一些小的改變需要注意下就ok了,下面這篇文章主要給大家介紹了關(guān)于如何在Springboot實(shí)現(xiàn)攔截器功能的相關(guān)資料,需要的朋友可以參考下2022-06-06

