一,祛除请求体属性字符串首尾空格
import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class StringTrimModule extends SimpleModule {
public StringTrimModule() {
addDeserializer(String.class, new StdScalarDeserializer<String>(String.class) {
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext ctx) throws IOException {
String value = jsonParser.getValueAsString();
if (StringUtils.isEmpty(value))
return value;
return value.trim();
}
});
}
}
二,bean和map的处理,可以利用fastJson哦;处理beanUtil的null值赋值很方便
package com.intellif.vesionbook.admin.utils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.CollectionUtils;
import java.lang.reflect.Field;
import java.util.*;
/**
* @Auther: yedongfeng
* @Date: 2020/7/8 18:19
* @Description:
*/
@Slf4j
public class BeanUtil {
public static String[] getNullPropertyNames (Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for(java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) emptyNames.add(pd.getName());
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
/**
* 忽略null值
* @param src
* @param target
*/
public static void CopyProperties(Object src, Object target) {
BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}
/**
* Bean转Map 包含父类信息
* @param bean
* @return
*/
public static Map<String, Object> transBean2Map(Object bean) {
if (bean == null) {
return null;
}
Map<String,Object>map = new HashMap<>();
final BeanWrapper src = new BeanWrapperImpl(bean);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for(java.beans.PropertyDescriptor pd : pds) {
map.put(pd.getName(),src.getPropertyValue(pd.getName()));
}
return map;
}
/**
* Bean转Map 不包含父类信息
* @param bean
* @return
*/
public static Map<String, Object> beanToMap(Object bean) {
if (bean == null) {
return null;
}
Map<String, Object> map = new HashMap<>();
// 得到类对象
Class userCla = bean.getClass();
/* 得到类中的所有属性集合 */
Field[] fs = userCla.getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
Field f = fs[i];
map.put(f.getName(),"");
f.setAccessible(true); // 设置些属性是可以访问的
Object val = new Object();
try {
val = f.get(bean);
// 得到此属性的值
map.put(f.getName(), val);// 设置键值
} catch (IllegalArgumentException e) {
log.info("bean 转 map 异常:{}", e.getMessage());
} catch (IllegalAccessException e) {
log.info("bean 转 map 异常:{}", e.getMessage());
}
}
return map;
}
public static <T> List<T> objToBeanList (Object src,Class<T> clazz){
if(null == src){
return null;
}
String json = JSONObject.toJSONString(src);
List<T> ts = JSONObject.parseArray(json, clazz);
return ts;
}
public static <T> T objToBean (Object src,Class<T> clazz){
if(null == src){
return null;
}
String json = JSONObject.toJSONString(src);
T t = JSONObject.parseObject(json, clazz);
return t;
}
public static <T> List<T> objToList(List src, Class<T> tClass) {
if(!CollectionUtils.isEmpty(src)){
List<T> list = Lists.newArrayList();
src.forEach(
x->{
try {
T t = tClass.newInstance();
BeanUtil.CopyProperties(x,t);
list.add(t);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
);
return list;
}
return null;
}
}
三,beanUtil有时候处理转换也不方便,不如用mapstruct试试,以下是整理的一个基类,使用时候继承即可使用基本方法
import org.mapstruct.*;
import java.util.List;
import java.util.stream.Stream;
@MapperConfig
public interface BaseMapping<SOURCE, TARGET> {
/**
* 映射同名属性
*/
TARGET sourceToTarget(SOURCE var1);
/**
* 反向,映射同名属性
*/
@InheritInverseConfiguration(name = "sourceToTarget")
SOURCE targetToSource(TARGET var1);
/**
* 映射同名属性,集合形式
*/
@InheritConfiguration(name = "sourceToTarget")
List<TARGET> sourceToTarget(List<SOURCE> var1);
/**
* 反向,映射同名属性,集合形式
*/
@InheritConfiguration(name = "targetToSource")
List<SOURCE> targetToSource(List<TARGET> var1);
/**
* 映射同名属性,集合流形式
*/
List<TARGET> sourceToTarget(Stream<SOURCE> stream);
/**
* 反向,映射同名属性,集合流形式
*/
List<SOURCE> targetToSource(Stream<TARGET> stream);
}
使用时候 比如:
/**
* @Auther: yedongfeng
* @Date: 2020/9/4 13:32
* @Description:
*/
@Mapper(componentModel = "spring")
public interface PosConvertMapper extends BaseMapping<SynPosCouponVO, Coupon> {
}
三,微信获取小程序码的工具类,此处获取的是一个图片文件,可根据需求后续处理
package *.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.*;
import java.io.*;
import java.net.ConnectException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class WeixinUtil implements ApplicationContextAware {
/**
* 获取接口调用凭证
* @return
*/
private static final String WECHAT_ACCESS_TOKEN_GET_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
/**
* 获取小程序码
* @return
*/
private static final String WECHAT_PROGRAM_CODE_GET_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s";
/**
* 有限测试接口
*/
private static final String WECHAT_PROGRAM_CODE_GET_LIMIT_URL = "https://api.weixin.qq.com/wxa/getwxacode?access_token=%s";
private static StringRedisTemplate redisTemplate;
private static RestTemplate rest;
/**
* 发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
// if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (ConnectException ce) {
log.error("Weixin server connection timed out.");
} catch (Exception e) {
log.error("https request error:{}", e);
}
return jsonObject;
}
public static File getProgramCode(String path,String scene,String appId,String secret) throws BusinessException {
//在获取小程序码之前,首先获取token
String token = redisTemplate.opsForValue().get("BOOK:ADMIN:WECHAT:ACCESSTOKEN");
if(StringUtils.isEmpty(token)){
AccessToken accessToken = null;
String requestUrl = String.format(WECHAT_ACCESS_TOKEN_GET_URL, appId,secret);
JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "GET", null);
// 如果请求成功
if (null != jsonObject) {
try {
accessToken = new AccessToken();
accessToken.setToken(jsonObject.getString("access_token"));
accessToken.setExpiresIn(jsonObject.getIntValue("expires_in"));
} catch (JSONException e) {
accessToken = null;
// 获取token失败
log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getIntValue("errcode"), jsonObject.getString("errmsg"));
}
}
token = accessToken.getToken();
redisTemplate.opsForValue().set("BOOK:ADMIN:WECHAT:ACCESSTOKEN",token, accessToken.getExpiresIn()-5,TimeUnit.SECONDS);
}
InputStream inputStream = null;
OutputStream outputStream = null;
try {
// String url = String.format(WECHAT_PROGRAM_CODE_GET_URL,token );
String url = String.format(WECHAT_PROGRAM_CODE_GET_LIMIT_URL,token );
Map<String, Object> param = new HashMap<>();
// param.put("scene",scene);
// param.put("page", path);//无限
param.put("path", path); //有限
param.put("width", 430);
param.put("auto_color", false);
Map<String, Object> line_color = new HashMap<>();
line_color.put("r", 0);
line_color.put("g", 0);
line_color.put("b", 0);
param.put("line_color", line_color);
param.put("is_hyaline",false);
log.info("调用生成微信URL接口传参:" + param);
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
HttpEntity requestEntity = new HttpEntity(JSON.toJSONString(param), headers);
ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
log.info("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
byte[] result = entity.getBody();
String res = new String(result,"utf-8");
if(isjson(res)){
if(JSONObject.parseObject(res).getInteger("errcode")==40001){//凭证失效
redisTemplate.delete("BOOK:ADMIN:WECHAT:ACCESSTOKEN");
return getProgramCode(path,scene,appId,secret);
}
throw new BusinessException(ResultCodeEnums.MINCODE_OBTAIN_FAIL);
}
String fileName = UUIDGenerate.generateShortUuid()+"minCode.png";
File file = new File(fileName);
inputStream = new ByteArrayInputStream(result);
outputStream = new FileOutputStream(file);
int len = 0;
byte[] buf = new byte[1024];
while ((len = inputStream.read(buf, 0, 1024)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.flush();
return file;
} catch (Exception e) {
log.error("调用小程序生成微信永久小程序码URL接口异常", e);
throw new BusinessException(ResultCodeEnums.MINCODE_OBTAIN_FAIL);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.rest = applicationContext.getBean("restTemplate",RestTemplate.class);
this.redisTemplate = applicationContext.getBean("stringRedisTemplate",StringRedisTemplate.class);
}
public static class MyX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
public static boolean isjson(String string){
try {
JSONObject jsonStr= JSONObject.parseObject(string);
return true;
} catch (Exception e) {
return false;
}
}
}
四,DES AES RSA加密解密
package *.utils;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.Key;
import java.util.Arrays;
import java.util.Base64;
public class DESUtil {
// /**
// * 偏移变量,固定占8位字节
// */
// private final static String IV_PARAMETER = "10850078";
/**
* 密钥算法
*/
private static final String ALGORITHM = "DES";
/**
* 加密/解密算法-工作模式-填充模式
*/
private static final String CIPHER_ALGORITHM = "DES/ECB/NoPadding";
/**
* 默认编码
*/
private static final String CHARSET = "utf-8";
/**
* 生成key
*
* @param password
* @return
* @throws Exception
*/
private static Key generateKey(String password) throws Exception {
DESKeySpec dks = new DESKeySpec(password.getBytes(CHARSET));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
return keyFactory.generateSecret(dks);
}
/**
* DES加密字符串
*
* @param password 加密密码,长度不能够小于8位
* @param data 待加密字符串
* @return 加密后内容
*/
public static String encrypt(String password, String data) {
if (password == null || password.length() < 8) {
throw new RuntimeException("加密失败,key不能小于8位");
}
if (data == null){
return null;
}
try {
Key secretKey = generateKey(password);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
//IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
//cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
//ECB模式不需要偏移量
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] dataBytes = data.getBytes(CHARSET);
int blockSize = cipher.getBlockSize();
//计算填充长度 blockSize 8个字节
int length = dataBytes.length;
//计算需填充长度 NoPadding不填充,ZreoPadding 需要我们自己手动实现
if (length % blockSize != 0) {
length = length + (blockSize - (length % blockSize));
byte[] temp = new byte[length];
//填充
Arrays.fill(temp,(byte)0);
//copy
System.arraycopy(dataBytes, 0, temp, 0, dataBytes.length);
dataBytes = temp;
}
// if (length % blockSize != 0) {
// int groups = length / blockSize + (length % blockSize != 0 ? 1 : 0);
// byte[] temp = new byte[groups * blockSize];
// Arrays.fill(temp, (byte) 0);
// System.arraycopy(dataBytes, 0, temp, 0, dataBytes.length);
// dataBytes = temp;
// }
byte[] bytes = cipher.doFinal(dataBytes);
return new String(Base64.getEncoder().encode(bytes));
} catch (Exception e) {
e.printStackTrace();
return data;
}
}
/**
* DES解密字符串
* @param password 解密密码,长度不能够小于8位
* @param data 待解密字符串
* @return 解密后内容
*/
public static String decrypt(String password, String data) {
if (password == null || password.length() < 8) {
throw new RuntimeException("加密失败,key不能小于8位");
}
if (data == null)
return null;
try {
Key secretKey = generateKey(password);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
// IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
// cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes(CHARSET))), CHARSET);
} catch (Exception e) {
e.printStackTrace();
return data;
}
}
public static void main(String[] args) {
// String oldStr = "03125889b46878af-bdc6-4b4a-b7b7-5bcd1a1348f0";
// System.out.println("原字符串:" + oldStr);
// String encrypt = DESUtil.encrypt(key, oldStr);
// System.out.println("加密后字符串:" + encrypt);
String decrypt = DESUtil.decrypt("10850078", "ZMndz91nylQ=");
System.out.println("解密后字符串:" + decrypt);
}
}
package com.intellif.vesionbook.admin.utils;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.symmetric.AES;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
public class SecurityUtils {
private static final String RSA_ALGORITHM = "RSA";
private static final String AES_ALGORITHM = "AES";
private static final String CIPHER_MODE = "AES/CBC/PKCS5Padding";
private static final Logger logger = LoggerFactory.getLogger(SzbookUtils.class);
/**
* 生成MD5
*
* @param val 参数
* @return MD5字符串
*/
public static String generateMD5Str(Map<String, Object> val) {
// key按照字母排序
// 用其他的key生成MD5字符串
val.remove("MD5");
Set<String> keys = val.keySet();
if (keys.size() == 0) {
return null;
}
Set<String> sortKeys = new TreeSet<String>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
sortKeys.addAll(keys);
// 生成加密字符串
StringBuilder keysStr = new StringBuilder("");
for (String key : sortKeys) {
Object value = val.get(key);
keysStr.append(key + "=" + value + "&");
}
keysStr.append("MD5Key=" + SzbookConfig.MD5_KEY);
// keysStr.append("MD5Key=" +"XkzFNLgy6vp7Ot8ujTUDZSfJ9l4PnBeE");
// 生成MD5字符串(大写)
return DigestUtils.md5DigestAsHex(keysStr.toString().getBytes()).toUpperCase();
}
/**
* RSA算法加密
*
* @param str 加密字符串
* @param publicKeyStr 公钥字符串
* @return 加密后的字节数组
*/
public static byte[] rsaEncrypt(String str, String publicKeyStr) {
RSA rea = new RSA(null, getPublicKey(publicKeyStr, RSA_ALGORITHM));
return rea.encrypt(StrUtil.bytes(str, StandardCharsets.UTF_8), KeyType.PublicKey);
}
/**
* 生成公钥
*
* @param key public_key
* @param algorithm 算法
* @return 公钥
* @throws Exception
*/
public static PublicKey getPublicKey(String key, String algorithm) {
try {
byte[] keyBytes = Base64.decodeBase64(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("public_key error");
}
}
/**
* 生成临时对称密钥(16字节)
*
* @return 临时对称密钥
*/
public static String generateTempEncryptKey() {
return IdUtil.simpleUUID().substring(0, 16);
}
public static long getTimestamp() {
long milli = System.currentTimeMillis() + 8 * 3600 * 1000;
return (milli * 10000) + 621355968000000000L;
}
/**
* AES解密
*
* @param encryptContent 待解密的字符串
* @param password 对称秘钥
* @return 解密后的字符串
*/
public static String decrypt(byte[] encryptContent, String password) {
try {
Cipher cipher = Cipher.getInstance(CIPHER_MODE);
IvParameterSpec iv = new IvParameterSpec(password.getBytes());
byte[] raw = password.getBytes(StandardCharsets.UTF_8);
//设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(raw, AES_ALGORITHM), iv);
//执行解密操作
byte[] result = cipher.doFinal(encryptContent);
// 解密后的字符串
return new String(result, StandardCharsets.UTF_8);
} catch (Exception e) {
logger.error("AES decrypt fail", e);
return null;
}
}
/**
* AES加密
*
* @param encryptContent 待加密的字符串
* @param password 对称秘钥
* @return 加密后的字符串
*/
public static byte[] encrypt(byte[] encryptContent, String password) {
try {
byte[] raw = password.getBytes(StandardCharsets.UTF_8);
IvParameterSpec iv = new IvParameterSpec(password.getBytes());
AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, new SecretKeySpec(raw, AES_ALGORITHM), iv);
byte[] result = aes.encrypt(encryptContent);
return result;
} catch (Exception e) {
logger.error("AES encrypt fail:{}", e);
return null;
}
}
/**
* 校验MD5
*
* @param md5Input MD5
* @param objectInput 要比较的对象
* @return ture or false
*/
public static boolean verifyMD5Hash(String md5Input, Object objectInput) throws Exception {
String hashStr = generateMD5Str(Utils.beanToMap(objectInput));
return md5Input.equals(hashStr);
}
/**
* 将hex字符串转换成字节数组 *
*
* @param inputString 16进制的字符串
* @return 字节数组
*/
public static byte[] hex2byte(String inputString) {
if (inputString == null || inputString.length() < 2) {
return new byte[0];
}
inputString = inputString.toLowerCase();
int l = inputString.length() / 2;
byte[] result = new byte[l];
for (int i = 0; i < l; ++i) {
String tmp = inputString.substring(2 * i, 2 * i + 2);
result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
}
return result;
}
}
五,文件工具类
package com.intellif.vesionbook.admin.utils;
import org.apache.commons.lang.StringUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Enumeration;
public class FileUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);
/**
* 解压
* @param sourceFile 带解压的文件
* @param destPath 解压后的路径
*/
public static File unZip(String sourceFile, String destPath) throws Exception {
ZipFile zipFile = new ZipFile(sourceFile,"gbk");
Enumeration zList = zipFile.getEntries(); //得到zip包里的所有元素
ZipEntry ze;
File srcFile = null;
byte[] buf = new byte[1024];
while (zList.hasMoreElements()) {
ze = (ZipEntry) zList.nextElement();
if (ze.isDirectory()) {
System.out.println(ze.getName());
if("封面/".equalsIgnoreCase(ze.getName())) {
LOGGER.info("打开zip文件里的文件夹:" + ze.getName() + "skipped...");
continue;
}else{
LOGGER.error("非法的模板格式");
throw new IllegalArgumentException("非法的模板格式");
}
}
OutputStream outputStream = null;
InputStream inputStream = null;
try {
//以ZipEntry为参数得到一个InputStream,并写到OutputStream中
File realFile = getRealFileName(destPath, ze.getName());
System.out.println(realFile.getAbsolutePath());
if (ze.getName().lastIndexOf(".xlsx") != -1) {
srcFile = realFile;
}
outputStream = new BufferedOutputStream(new FileOutputStream(realFile));
inputStream = new BufferedInputStream(zipFile.getInputStream(ze));
int readLen;
while ((readLen = inputStream.read(buf, 0, 1024)) != -1) {
outputStream.write(buf, 0, readLen);
}
inputStream.close();
outputStream.close();
} catch (Exception e) {
LOGGER.error("解压失败", e);
throw new IOException("解压失败:" + e.toString());
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
zipFile.close();
return srcFile;
}
/**
* 给定根目录,返回一个相对路径所对应的实际文件名.
*
* @param path 指定根目录
* @param absFileName 相对路径名,来自于ZipEntry中的name
* @return java.io.File 实际的文件
*/
private static File getRealFileName(String path, String absFileName) {
String[] dirs = absFileName.split("/", absFileName.length());
File ret = new File(path);// 创建文件对象
if (dirs.length > 1) {
for (int i = 0; i < dirs.length - 1; i++) {
ret = new File(ret, dirs[i]);
}
}
if (!ret.exists()) { // 检测文件是否存在
ret.mkdirs(); // 创建此抽象路径名指定的目录
}
ret = new File(ret, dirs[dirs.length - 1]);// 根据 ret 抽象路径名和 child 路径名字符串创建一个新 File 实例
return ret;
}
public static void deleteFile(File file) {
if (file.exists()) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
deleteFile(files[i]);
}
}
}
file.delete();
}
/**
* 把一个文件转化为byte字节数组。
*/
public static byte[] fileConvertToByteArray(String filePath) {
byte[] data = null;
try {
FileInputStream fis = new FileInputStream(filePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[1024];
while ((len = fis.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
data = baos.toByteArray();
fis.close();
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
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.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 判断文件大小
* @param len
* 文件长度
* @param size
* 限制大小
* @param unit
* 限制单位(B,K,M,G)
* @return
*/
public static boolean checkFileSize(Long len, int size, String unit) {
double fileSize = 0;
if ("B".equals(unit.toUpperCase())) {
fileSize = (double) len;
} else if ("K".equals(unit.toUpperCase())) {
fileSize = (double) len / 1024;
} else if ("M".equals(unit.toUpperCase())) {
fileSize = (double) len / 1048576;
} else if ("G".equals(unit.toUpperCase())) {
fileSize = (double) len / 1073741824;
}
if (fileSize > size) {
return false;
}
return true;
}
/**
* 获得控制台用户输入的信息
* @return
* @throws IOException
*/
public static String getInputMessage() throws IOException{
System.out.println("请输入您的命令∶");
byte buffer[]=new byte[1024];
int count= 0;
try {
count = System.in.read(buffer);
char[] ch=new char[count-2];//最后两位为结束符,删去不要
for(int i=0;i<count-2;i++)
ch[i]=(char)buffer[i];
String str=new String(ch);
return str;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
*以流的方式复制文件
* @param src
* @param dest
* @throws IOException
*/
public void copyFile(String src,String dest) throws IOException{
FileInputStream in=new FileInputStream(src);
File file=new File(dest);
if(!file.exists())
file.getParentFile().mkdirs();
file.createNewFile();
FileOutputStream out=new FileOutputStream(file);
int c;
byte buffer[]=new byte[1024];
while((c=in.read(buffer))!=-1){
for(int i=0;i<c;i++)
out.write(buffer[i]);
}
in.close();
out.close();
}
/**
* 利用PrintStream写文件
* @param path
* @param content
*/
public static void PrintStream(String path,String content){
try {
//"D:/test.txt"
FileOutputStream out=new FileOutputStream(path);
PrintStream p=new PrintStream(out);
for(int i=0;i<content.length();i++)
p.println(content.charAt(i));
} catch (FileNotFoundException e){
e.printStackTrace();
}
}
/**
* 利用StringBuffer写文件
* @param path
* @param content
*/
public static void StringBuff(String path,String content) throws IOException{
File file=new File(path);
if(!file.exists()){
file.getParentFile().mkdirs();
file.createNewFile();
}
FileOutputStream out=new FileOutputStream(file,true);
StringBuffer sb=new StringBuffer();
if(StringUtils.isNotBlank(content)){
sb.append(content);
out.write(sb.toString().getBytes("utf-8"));
}
out.close();
}
/**
* 文件重命名
*/
public static void renameFile(String path,String oldname,String newname){
if(!oldname.equals(newname)){//新的文件名和以前文件名不同时,才有必要进行重命名
File oldfile=new File(path+"/"+oldname);
File newfile=new File(path+"/"+newname);
if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名
System.out.println(newname+"已经存在!");
else{
oldfile.renameTo(newfile);
}
}
}
/**
* 文件转移目录
* 转移文件目录不等同于复制文件,
* 复制文件是复制后两个目录都存在该文件,而转移文件目录则是转移后,只有新目录中存在该文件
* @param filename
* @param oldpath
* @param newpath
* @param cover
* @return
*/
public String changeDirectory(String filename, String oldpath, String newpath, boolean cover) throws IOException {
if(!oldpath.equals(newpath)){
File oldfile=new File(oldpath+"/"+filename);
File newfile=new File(newpath+"/"+filename);
if(newfile.exists()){//若在待转移目录下,已经存在待转移文件
if(cover) {//覆盖
oldfile.renameTo(newfile);
}
else{
System.out.println("在新目录下已经存在:"+filename);
}
}
else{
oldfile.renameTo(newfile);
}
}
return null;
}
/**
* 利用FileInputStream读取文件
* @param path
* @return
* @throws IOException
*/
public static String FileInputStreamDemo(String path) throws IOException{
File file=new File(path);
if(!file.exists()||file.isDirectory())
throw new FileNotFoundException();
FileInputStream fis=new FileInputStream(file);
byte[] buf = new byte[1024];
StringBuffer sb=new StringBuffer();
while((fis.read(buf))!=-1){
sb.append(new String(buf));
buf=new byte[1024];//重新生成,避免和上次读取的数据重复
}
return sb.toString();
}
/**
* 利用bufferReader读取文件
* @param path
* @return
* @throws IOException
*/
public static String BufferedReaderDemo(String path) throws IOException{
File file=new File(path);
if(!file.exists()||file.isDirectory())
throw new FileNotFoundException();
BufferedReader br=new BufferedReader(new FileReader(file));
String temp=null;
StringBuffer sb=new StringBuffer();
temp=br.readLine();
while(temp!=null){
sb.append(temp+" ");
temp=br.readLine();
}
return sb.toString();
}
/**
* 利用dom4j读取xml文件
* @param path
* @return
* @throws DocumentException
* @throws IOException
*/
public Document readXml(String path) throws DocumentException, IOException{
File file=new File(path);
BufferedReader bufferedreader = new BufferedReader(new FileReader(file));
SAXReader saxreader = new SAXReader();
Document document = (Document)saxreader.read(bufferedreader);
bufferedreader.close();
return document;
}
/**
* 创建文件(夹)
* @param path
* @return
* @throws IOException
*/
public static File createDirFile(String path) throws IOException {
File dir=new File(path);
if(!dir.exists()){
dir.getParentFile().mkdirs();
dir.createNewFile();
}
return dir;
}
/**
* 删除文件
* @param path 包含文件名
*/
public static void delFile(String path){
File file=new File(path);
if(file.exists()&&file.isFile())
file.delete();
}
}