Java將資料生成XML檔案並進行壓縮成GZ格式
阿新 • • 發佈:2020-12-14
近期和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發生異常");
}
}
按照我提供的工具類,根據自己的實際需求基本上都可以使用
關注我的微信公眾號