1.pom文件
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/xerces/xercesImpl -->
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.9.1</version>
</dependency>
<!-- JSONObject对象依赖的jar包 开始-->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.2.3</version>
<classifier>jdk15</classifier><!-- jdk版本 -->
</dependency>
<!-- Json依赖架包下载结束 -->
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
2.将查询数据封装到XML文件中,并进行格式化处理
package com.zcl.util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* sql查询数据封装到xml文件中
*/
public class DataToXml {
//默认值
private static final String JSON="json";
private static final String XML="xml";
/**
* 工具类入口
* @param type 数据类型 json / xml
* @return 字符串
*/
public static void DataToJsonOrXml(Object obj,String type) throws Exception{
//大小写不影响
String str="";
if(JSON.equalsIgnoreCase(type)&&JSON.equals(type)){
//生成json数据
str=toJsonString(obj);
}else if(XML.equalsIgnoreCase(type)&&XML.equals(type)){
//生成xml数据
str=toXml(obj);
}else{
//默认使用 json , 参数错误的话 ,默认 为json
str=toJsonString(obj);
}
str = XmlFormatter.format(str);
writeToXml(str);
}
/**
* 转 json 对象
* @param obj 数据
* @return json对象 字符串
*/
private static String toJsonString(Object obj){
if(obj==null) {
obj="";
}
Map<String, Object> map=toKeyVal(obj);
JSONObject jsonObject=JSONObject.fromObject(map);
return jsonObject.toString();
}
/**
* 转xml 格式 :字符串拼装的格式
* @param obj 数据
* @return xml数据
*/
private static String toXml(Object obj){
if(obj==null) {
obj="";
}
Map<String,Object> map=toKeyVal(obj);
JSONObject object=JSONObject.fromObject(map);
StringBuilder builder=new StringBuilder("<?xml version='1.0' encoding='UTF-8'?>");
builder.append("<root>");
builder.append(mapToxml(object));
builder.append("</root>");
return builder.toString();
}
/**
* 用来封装数据
* @param obj 数据
* @return
*/
private static Map<String, Object> toKeyVal(Object obj){
Map<String,Object> map=new HashMap<String, Object>();
map.put("data", obj);
return map;
}
/**
* 生成 xml
* @param object
* @return
*/
private static String mapToxml(JSONObject object){
StringBuilder builder=new StringBuilder();
@SuppressWarnings("unchecked")
Iterator<String> iterator=object.keys();
while(iterator.hasNext()){
String key=iterator.next();
builder.append("<"+key+">");
if(object.get(key) instanceof JSONObject){
//如果是 JSONObject的话
//递归 调用
builder.append(mapToxml((JSONObject) object.get(key)));
}else if(object.get(key) instanceof JSONArray){
//如果是 JSONArray的话
StringBuilder builder2=new StringBuilder();
JSONArray array=(JSONArray) object.get(key);
if(array.isArray()){
int i=0;
for(Object obj : array) {
JSONObject objitem=(JSONObject) obj;
String attr="num='"+i+"'";
builder2.append("<item "+attr+">");
builder2.append(mapToxml(objitem));
builder2.append("</item>");
i++;
}
}
builder.append(builder2.toString());
}else{
builder.append(object.get(key));
}
builder.append("</"+key+">");
}
return builder.toString();
}
private static void writeToXml(String str) throws Exception{
//项目根路径
String relativelyPath=System.getProperty("user.dir");
String fileName = relativelyPath+"\\"+new SimpleDateFormat("yyyyMMdd").format(new Date())+".xml";
//1.生成xml文件
FileWriter fw=new FileWriter(fileName);
BufferedWriter bw=new BufferedWriter(fw);
bw.write(str);
bw.close();
fw.close();
}
}
3.XML文件的格式化操作
package com.zcl.util;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
/**
* 格式化xml
*/
public class XmlFormatter {
public static String format(String unformattedXml) {
try {
final Document document = parseXmlFile(unformattedXml);
OutputFormat format = new OutputFormat(document);
format.setLineWidth(65);
format.setIndenting(true);
format.setIndent(2);
Writer out = new StringWriter();
XMLSerializer serializer = new XMLSerializer(out, format);
serializer.serialize(document);
return out.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static Document parseXmlFile(String in) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(in));
return db.parse(is);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
} catch (SAXException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
4.DES方式加密和解密文件
package com.zcl.util;
import org.apache.commons.codec.binary.Hex;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class DESCryptoXml {
/**
* 文件加密
*/
public static void encrypt(String fileName) {
try {
String key = "abf894ba2a0e798f";
// 再把我们的字符串转变为字节数组,可以用于另一方使用,验证
byte[] decodeHex = Hex.decodeHex(key.toCharArray());
// 生成密钥对象
SecretKeySpec secretKeySpec = new SecretKeySpec(decodeHex, "DES");
// 获取加解密实例
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
// 初始化加密模式
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
// 读入并加密文件
try {
// 输入流
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(fileName));
// 输出流
//新文件名
String fileNewName = fileName.substring(0,fileName.indexOf("."))+"Encrypt"+fileName.substring(fileName.indexOf("."));
CipherOutputStream out = new CipherOutputStream(
new BufferedOutputStream(new FileOutputStream(fileNewName)), cipher);
int i;
do {
i = in.read();
if (i != -1)
out.write(i);
} while (i != -1);
in.close();
out.close();
System.out.println("success when encrypt the file");
} catch (Exception ey5) {
System.out.println("error when encrypt the file");
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 文件解密
* @param fileName
*/
public static void decrypt(String fileName) {
try {
String key = "abf894ba2a0e798f";
// 再把我们的字符串转变为字节数组,可以用于另一方使用,验证
byte[] decodeHex = Hex.decodeHex(key.toCharArray());
// 生成密钥对象
SecretKeySpec secretKeySpec = new SecretKeySpec(decodeHex, "DES");
// 获取加解密实例
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
// 初始化加密模式
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
try {
// 输入流
CipherInputStream in = new CipherInputStream(
new BufferedInputStream(new FileInputStream(fileName)), cipher);
// 输出流
//新文件名
String fileNewName = fileName.substring(0,fileName.indexOf("."))+"Decrypt"+fileName.substring(fileName.indexOf("."));
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(fileNewName));
int i;
do {
i = in.read();
if (i != -1)
out.write(i);
} while (i != -1);
in.close();
out.close();
System.out.println("success when decrypt the file");
} catch (Exception ey5) {
System.out.println("error when decrypt the file");
}
}catch (Exception e){
e.printStackTrace();
}
}
/***
* 生成秘钥字符串
*/
public static void main(String[] args) throws Exception{
// 以DES的方式初始化Key生成器
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
keyGenerator.init(56);// 设置密钥的长度为56位
// 生成一个Key
SecretKey generateKey = keyGenerator.generateKey();
// 转变为字节数组
byte[] encoded = generateKey.getEncoded();
// 生成密钥字符串
String encodeHexString = Hex.encodeHexString(encoded);
System.out.println("Key : " + encodeHexString);
}
}
5.测试
@Test
public void shouldAnswerWithTrue() throws Exception
{
/* List<Object> list = new ArrayList<>();
Map<String,String> map1 = new HashMap<>();
map1.put("username","张三");
map1.put("password","李四");
Map<String,String> map2 = new HashMap<>();
map2.put("username","张三");
map2.put("password","李四");
list.add(map1);
list.add(map2);*/
//第一步:生成xml文件
//DataToXml.DataToJsonOrXml(list,"xml");
//加密
//DESCryptoXml.encrypt("F:\\IDEAWorkspaces\\ceshiDataToXml\\20180822.xml");
//解密
//DESCryptoXml.decrypt("F:\\IDEAWorkspaces\\ceshiDataToXml\\20180822Encrypt.xml");
}