Java将数据生成XML文件并进行压缩成GZ格式
近期和PC端对接接口,在线上环境经常出现PC端接口拉取数据时后台负载高的情况,为了解决这个问题,我们将接口转换成xml文件格式,每当PC客户端启动时会拉取服务端最新的xml文件,达到很好的用户体验。
1、集成Maven
<dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.12</version> </dependency>
xstream注解解释: @XStreamAlias(“id”):将序列化中的类全量名称,用别名替换。
2、工具类
生成xml文件
public static <T> void listObjectToXmlFile(List<T> list, String path, String fileName, Integer tradeDate, boolean isCompress) { XStream xStream = new XStream(new DomDriver("UTF-8")); xStream.autodetectAnnotations(true); xStream.registerConverter(new DateConverter("yyyy-MM-dd HH:mm:ss", null, TimeZone.getTimeZone("GMT+8"))); String xml = xStream.toXML(list); String realPath = path + tradeDate; File dir = new File(realPath); if (!dir.exists()) { // 判断目录是否存在 dir.mkdir(); } String pathName = realPath + File.separator + fileName; //创建文件 File file = new File(pathName); if (file.exists()) { file.delete(); } try { file.createNewFile(); } catch (IOException e) { log.error("创建文件发生错误"); } //写入数据 FileOutputStream out = null; OutputStreamWriter outw = null; try { out = new FileOutputStream(file); outw = new OutputStreamWriter(out, "UTF-8"); try { outw.write(xml); } catch (IOException e) { log.error("生成文件发生错误"); } finally { outw.close(); out.close(); } } catch (Exception e1) { log.error("FileNotFoundException"); } //压缩文件 if (isCompress) doCompressFile(file, realPath); }
将xml文件进行压缩
/** * 压缩xml文件成.gz * * @param source */ public static void doCompressFile(File source, String realPath) { String realGzName = source.getName() + Constant.GZ_SUFFIX; String pathName = realPath + File.separator + realGzName; //创建文件 File target = new File(pathName); if (target.exists()) { target.delete(); } try { target.createNewFile(); } catch (IOException e) { log.error("创建文件发生错误"); } FileInputStream in = null; GZIPOutputStream out = null; try { in = new FileInputStream(source); out = new GZIPOutputStream(new FileOutputStream(target)); byte[] buf = new byte[10240]; int len = 0; try { while (((in.available() > 10240) && (in.read(buf)) > 0)) { out.write(buf); } len = in.available(); in.read(buf, 0, len); out.write(buf, 0, len); out.flush(); } catch (IOException e) { log.error("IOException发生异常"); } finally { in.close(); out.close(); } } catch (FileNotFoundException e) { log.error("FileNotFoundException发生异常"); } catch (IOException e) { log.error("IOException发生异常"); } }
按照我提供的工具类,根据自己的实际需求基本上都可以使用