实体类(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();
}
}
}
}
方法补充
下面小编为大家整理了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 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();
}
}
}到此这篇关于java获取压缩文件中的xml并解析保存到数据库的文章就介绍到这了,更多相关java xml获取与解析内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论