JAVA常用得工具类大全《持续更新》
文章目录
- 1.时间工具类
- 2.bean工具类
- 2. 分页工具类
- 3.Token工具类
- 4.用户详情工具类
- 5.远程请求工具类
- 6.BigDecimal工具类
- 7.XML工具类
- 8.zip工具类
本文档只是为了留档方便以后工作运维,或者给同事分享文档内容比较简陋命令也不是特别全,不适合小白观看,如有不懂可以私信,上班期间都是在得
记录一些常用得工具类
1.时间工具类
package com.xhao.farmework.utils;
import com.xhao.farmework.constant.DateConstant;
import java.time.LocalDate;
import java.time.Year;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
/**
* 时间工具类
*
* @author XHao
*/
public class DateUtils {
/**
* 获取当前日期
* @return LocalDate
*/
public static LocalDate getToDay() {
return LocalDate.now();
}
/**
* 获取当前日期
* @return LocalDate
*/
public static String getCurrentDay() {
return LocalDate.now().toString();
}
/**
* 获取今年过了多少天
* @return day
*/
public static int getDayOfYear(){
return getToDay().getDayOfYear();
}
/**
* 获取当天月份
* @return 月份
*/
public static int getMonth(){
return getToDay().getMonthValue();
}
/**
* 获取当天月份
* @return 月份
*/
public static String getCurrentMonth(){
return getToDay().format(DateConstant.FORMATTER_MONTH);
}
/**
* 获取当前年份
* @return 年份
*/
public static int getYear(){
return getToDay().getYear();
}
/**
* 获取去年年份
* @return 年份
*/
public static String geLastYear(){
return String.valueOf(getYear() - 1);
}
/**
* 获取七天前日期
* @return 七天前日期
*/
public static String getLastWeek(){
return getToDay().minusDays(8).format(DateConstant.FORMATTER_DAY);
}
/**
* 获取上一个月日期
* @param dateStr 日期
* @return 上个月
*/
public static String getPreviousMonth(String dateStr) {
YearMonth date = YearMonth.parse(dateStr);
YearMonth previousMonth = date.minusMonths(1);
return previousMonth.toString();
}
/**
* 获取上一年日期
* @param dateStr 日期
* @return 上个月
*/
public static String getPreviousYear(String dateStr) {
Year date = Year.parse(dateStr);
Year previousYear= date.minusYears(1);
return previousYear.toString();
}
/**
* 获取下个月日期
* @param dateStr 日期
* @return 下个月
*/
public static String getNextMonth(String dateStr) {
YearMonth date = YearMonth.parse(dateStr);
YearMonth nextMonth = date.plusMonths(1);
return nextMonth.toString();
}
/**
* 获取前6个月日期
* @return 日期
*/
public static String getPreviousSevenMonth() {
YearMonth currentYearMonth = YearMonth.now();
YearMonth previousMonth = currentYearMonth.minusMonths(6);
return previousMonth.toString();
}
/**
* 获取昨天日期
* @return 日期
*/
public static String getLastDay() {
LocalDate yesterday = LocalDate.now().minusDays(1);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return yesterday.format(formatter);
}
/**
* 获取前天日期
* @return 日期
*/
public static String getLastTwoDay() {
LocalDate yesterday = LocalDate.now().minusDays(2);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return yesterday.format(formatter);
}
/**
* 获取近七天的日期
*/
public static List<String> getPreviousSevenDays() {
List<String> dateList = new ArrayList<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
for (int i = 7; i >= 1; i--) {
LocalDate date = LocalDate.now().minusDays(i);
String formattedDate = date.format(formatter);
dateList.add(formattedDate);
}
return dateList;
}
/**
* 获取当前减1天得月份
* @return 月份
*/
public static String getMinusTodayMonth(){
return getToDay().minusDays(1).format(DateConstant.FORMATTER_MONTH);
}
/**
* 获取上月
* @return 月份
*/
public static String getLastMonth(){
return getToDay().minusMonths(1).format(DateConstant.FORMATTER_MONTH);
}
/**
* 获取两个月前数据
* @return 月份
*/
public static String geTwoMonthsAgo(){
return getToDay().minusMonths(2).format(DateConstant.FORMATTER_MONTH);
}
/**
* 获取减一天得年份
* @return 年份
*/
public static int getMinusTodayYear(){
return getToDay().minusDays(1).getYear();
}
/**
* 获取之前月份
*/
public static List<String> getThisYearMonths() {
List<String> dateList = new ArrayList<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
for (int i = 5; i >= 0; i--) {
LocalDate date = LocalDate.now().minusMonths(i);
String formattedDate = date.format(formatter);
dateList.add(formattedDate);
}
return dateList;
}
}
2.bean工具类
package com.xhao.farmework.utils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* spring工具类 方便在非spring管理环境中获取bean
*
* @author xhao
*/
@Component
public final class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware
{
/** Spring应用上下文环境 */
private static ConfigurableListableBeanFactory beanFactory;
private static ApplicationContext applicationContext;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
{
SpringUtils.beanFactory = beanFactory;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
SpringUtils.applicationContext = applicationContext;
}
/**
* 获取对象
*
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws org.springframework.beans.BeansException
*
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException
{
return (T) beanFactory.getBean(name);
}
/**
* 获取类型为requiredType的对象
*
* @param clz
* @return
* @throws org.springframework.beans.BeansException
*
*/
public static <T> T getBean(Class<T> clz) throws BeansException
{
T result = (T) beanFactory.getBean(clz);
return result;
}
/**
* 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
*
* @param name
* @return boolean
*/
public static boolean containsBean(String name)
{
return beanFactory.containsBean(name);
}
/**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
*
* @param name
* @return boolean
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.isSingleton(name);
}
/**
* @param name
* @return Class 注册对象的类型
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.getType(name);
}
/**
* 如果给定的bean名字在bean定义中有别名,则返回这些别名
*
* @param name
* @return
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.getAliases(name);
}
/**
* 获取aop代理对象
*
* @param invoker
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getAopProxy(T invoker)
{
return (T) AopContext.currentProxy();
}
/**
* 获取当前的环境配置,无配置返回null
*
* @return 当前的环境配置
*/
public static String[] getActiveProfiles()
{
return applicationContext.getEnvironment().getActiveProfiles();
}
/**
* 获取当前的环境配置,当有多个环境配置时,只获取第一个
*
* @return 当前的环境配置
*/
public static String getActiveProfile()
{
final String[] activeProfiles = getActiveProfiles();
return StringUtils.isNotEmpty(activeProfiles) ? activeProfiles[0] : null;
}
/**
* 获取配置文件中的值
*
* @param key 配置文件的key
* @return 当前的配置文件的值
*
*/
public static String getRequiredProperty(String key)
{
return applicationContext.getEnvironment().getRequiredProperty(key);
}
}
2. 分页工具类
package com.xhao.xygrdsserver.farmework.utils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.ArrayList;
import java.util.List;
/**
* 分页工具类
* @author XHao
*/
public class PageUtils {
/**
* 创建分页对象
* @param <T> 分页项的类型
* @param pageSize 页面大小
* @param current 当前页码
* @return 分页对象
*/
public static <T> Page<T> getPage(Integer pageSize, Integer current) {
if (current == null) {
current = 1;
}
if (pageSize == null) {
pageSize = 10;
}
return new Page<>(current, pageSize);
}
/**
* 分页工具方法
*
* @param list 原始对象列表
* @param pageNo 当前页码 (从1开始)
* @param pageSize 每页显示的数量
* @param <T> 列表元素类型
* @return 当前页的对象列表
*/
public static <T> List<T> paginate(List<T> list, int pageNo, int pageSize) {
if (list == null || list.isEmpty() || pageNo <= 0 || pageSize <= 0) {
return new ArrayList<>();
}
// 总条目数
int totalItems = list.size();
int fromIndex = (pageNo - 1) * pageSize;
int toIndex = Math.min(fromIndex + pageSize, totalItems);
// 如果页码超出范围,则返回空列表
if (fromIndex >= totalItems) {
return new ArrayList<>();
}
return new ArrayList<>(list.subList(fromIndex, toIndex));
}
/**
* 计算总页数
*
* @param list 原始对象列表
* @param pageSize 每页显示的数量
* @param <T> 列表元素类型
* @return 总页数
*/
public static <T> int getTotalPages(List<T> list, int pageSize) {
if (list == null || list.isEmpty() || pageSize <= 0) {
return 0;
}
int totalItems = list.size();
return (int) Math.ceil((double) totalItems / pageSize);
}
/**
* 获取分页的总记录数
*
* @param list 原始对象列表
* @param <T> 列表元素类型
* @return 总记录数
*/
public static <T> int getTotalCount(List<T> list) {
if (list == null) {
return 0;
}
return list.size();
}
}
3.Token工具类
package com.xhao.xygrdsserver.farmework.utils;
import com.xhao.xygrdsserver.farmework.constant.TokenConstants;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
/**
* 令牌工具类
*
* @author XHao
*/
public class TokenUtils {
/**
* 创建令牌
*
* @param uuid uuid
* @return {@link String}
*/
public static String createToken(String uuid, String userType) {
return Jwts.builder().setId(uuid)
.claim("userType", userType)
.signWith(SignatureAlgorithm.HS512, TokenConstants.SECRET).compact();
}
/**
* 从令牌中获取数据声明
*
* @param token 令牌
* @return id
*/
public static String parseToken(String token) {
if (token.startsWith(TokenConstants.TOKEN_PREFIX)) {
token = token.replace(TokenConstants.TOKEN_PREFIX, "");
}
return Jwts.parser()
.setSigningKey(TokenConstants.SECRET)
.parseClaimsJws(token)
.getBody().getId();
}
}
4.用户详情工具类
package com.xhao.xygrdsserver.farmework.utils;
import cn.hutool.core.util.ObjectUtil;
import com.xhao.xygrdsserver.farmework.constant.UserInfoConstants;
import com.xhao.xygrdsserver.farmework.execption.LogicException;
import com.xhao.xygrdsserver.farmework.model.UserInfo;
import org.apache.poi.ss.formula.functions.T;
import java.util.List;
/**
* 用户信息跑龙套
* @author XHao
*/
public class UserInfoUtils {
/**
* 用户信息线程本地
*/
private static final InheritableThreadLocal<UserInfo> USERINFO_THREAD_LOCAL = new InheritableThreadLocal<>();
/**
* 获取用户信息
*
* @return {@link UserInfo}
*/
public static UserInfo getUserInfo() {
return USERINFO_THREAD_LOCAL.get();
}
/**
* 设置用户信息
*
* @param userInfo 用户信息
*/
public static void setUserInfo(UserInfo userInfo) {
USERINFO_THREAD_LOCAL.set(userInfo);
}
/**
* 得到系统类型
*
* @return {@link String}
*/
public static List<String> getSystemType() {
return ObjectUtil.isNull(getUserInfo().getSystemType()) ? null :getUserInfo().getSystemType();
}
/**
* 得到园区列表
*
* @return {@link String}
*/
public static List<String> getParkCode() {
return ObjectUtil.isNull(getUserInfo().getParkCode()) ? null :getUserInfo().getParkCode();
}
/**
* 得到告警权限
*
* @return {@link String}
*/
public static List<String> getWarning() {
return ObjectUtil.isNull(getUserInfo().getWarning()) ? null :getUserInfo().getWarning();
}
/**
* 得到车间列表
*
* @return {@link String}
*/
public static List<String> getPlantCode() {
return ObjectUtil.isNull(getUserInfo().getPlantCode()) ? null :getUserInfo().getPlantCode();
}
/**
* 得到园区标识集合
*
* @return 园区标识集合
*/
public static List<String> getParkCodes(){
return getUserInfo().getAuthoritiesList();
}
/**
* 设置系统类型
*
* @param systemType 系统类型
*/
public static void setSystemType(List<String> systemType) {
UserInfo userInfo = getUserInfo();
if (userInfo == null) {
userInfo = new UserInfo();
}
userInfo.setSystemType(systemType);
}
/**
* 删除
*/
public static void remove() {
USERINFO_THREAD_LOCAL.remove();
}
/**
* 得到用户id
*
* @return {@link String}
*/
public static Long getUserId() {
UserInfo userInfo = USERINFO_THREAD_LOCAL.get();
return userInfo == null ? null : userInfo.getId();
}
public static String getLoginKey(String loginUuid, String userType) {
String redisKey;
if (userType.equals(UserInfoConstants.XYG_PERSONNEL)) {
redisKey = UserInfoConstants.XYG_PERSONNEL;
} else {
throw new LogicException("用户类型不正确");
}
return redisKey + loginUuid;
}
}
5.远程请求工具类
package com.xhao.xygrdsserver.agv.util;
import com.alibaba.fastjson.JSONArray;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class ApiRequester {
public static JSONArray sendPost(String apiUrl, String param) {
try {
// 创建URL对象
URL url = new URL(apiUrl);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 设置请求头
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
// 启用输入输出流
connection.setDoOutput(true);
// 写入请求体
try (OutputStream os = connection.getOutputStream()) {
byte[] input = param.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// 获取响应状态码
// int responseCode = connection.getResponseCode();
// 读取响应
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
// System.out.println("Response Body: " + response.toString());
return JSONArray.parseArray(response.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package com.xhao.xygrdsserver.common.utils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* @author YLP
*/
public class SSLUtils {
/**
* 设置SSL协议跳过证书策略
*/
public static SSLConnectionSocketFactory ssl(){
try {
// 创建一个上下文(此处指定的协议类型似乎不是重点)
SSLContext ctx = SSLContext.getInstance("TLS");
// 创建一个跳过SSL证书的策略
X509TrustManager tm = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
};
// 使用上面的策略初始化上下文
ctx.init(null, new TrustManager[] { tm }, null);
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx,
new String[] { "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2" }, null, NoopHostnameVerifier.INSTANCE);
return ssf;
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
return null;
}
}
6.BigDecimal工具类
package com.xhao.xygrdsserver.common.utils;
import java.math.BigDecimal;
/**
* @Author xhao
* @Date 2023/8/31
* @Version 0.0.1
* @Note 计算数据工具类
*/
public class ArithmeticUtils {
private static final BigDecimal THOUSAND = new BigDecimal(1000);
private static final BigDecimal TEN_THOUSAND = new BigDecimal(10000);
/**
* 将万单位转换为普通
*
* @param bigDecimal 值
* @return BigDecimal
*/
public static BigDecimal convertOrdinary(BigDecimal bigDecimal) {
bigDecimal = bigDecimal.multiply(THOUSAND);
return bigDecimal;
}
/**
* 千单位
*
* @param bigDecimal 值
* @return BigDecimal
*/
public static BigDecimal convertThousand(BigDecimal bigDecimal) {
bigDecimal = bigDecimal.divide(THOUSAND);
return bigDecimal;
}
/**
* 万单位
*
* @param bigDecimal 值
* @return BigDecimal
*/
public static BigDecimal convertTenThousand(BigDecimal bigDecimal) {
bigDecimal = bigDecimal.divide(TEN_THOUSAND);
return bigDecimal;
}
}
7.XML工具类
package com.XHao.xygrdsserver.mq.util;
import cn.hutool.json.XML;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.XHao.xygrdsserver.mq.entity.XygMqStorage;
import com.XHao.xygrdsserver.mq.entity.param.XmlParam;
import com.XHao.xygrdsserver.mq.enums.HeaderEnum;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @ClassName: XmlUtil
* @Description: xml 解析与生成工具类
* @Author: XHao
* @Date: 2024/8/20 14:28
*/
public class XmlUtil {
/**
* XML节点转换JSON对象
*
* @param element 节点
* @param object 新的JSON存储
* @return JSON对象
*/
private static JSONObject xmlToJson(Element element, JSONObject object) {
List<Element> elements = element.elements();
for (Element child : elements) {
Object value = object.get(child.getName());
Object newValue;
if (child.elements().size() > 0) {
JSONObject jsonObject = xmlToJson(child, new JSONObject(true));
if (!jsonObject.isEmpty()) {
newValue = jsonObject;
} else {
newValue = child.getText();
}
} else {
newValue = child.getText();
}
List<Attribute> attributes = child.attributes();
if (!attributes.isEmpty()) {
JSONObject attrJsonObject = new JSONObject();
for (Attribute attribute : attributes) {
attrJsonObject.put(attribute.getName(), attribute.getText());
attrJsonObject.put("content", newValue);
}
newValue = attrJsonObject;
}
if (newValue != null) {
if (value != null) {
if (value instanceof JSONArray) {
((JSONArray) value).add(newValue);
} else {
JSONArray array = new JSONArray();
array.add(value);
array.add(newValue);
object.put(child.getName(), array);
}
} else {
object.put(child.getName(), newValue);
}
}
}
return object;
}
/**
* XML字符串转换JSON对象
*
* @param xmlStr XML字符串
* @return JSON对象
*/
public static JSONObject xmlToJson(String xmlStr) {
JSONObject result = new JSONObject(true);
SAXReader xmlReader = new SAXReader();
try {
Document document = xmlReader.read(new StringReader(xmlStr));
Element element = document.getRootElement();
return xmlToJson(element, result);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* XML文件转换JSON对象
*
* @param xmlString xml字符串
* @param node 选择节点
* @return JSON对象
*/
public static JSONObject xmlToJson(String xmlString, String node) {
JSONObject result = new JSONObject(true);
SAXReader xmlReader = new SAXReader();
try {
//将给定的String文本解析为XML文档并返回新创建的document
org.dom4j.Document document = DocumentHelper.parseText(xmlString);
// Document document = xmlReader.read(file);
Element element;
if (StringUtils.isBlank(node)) {
element = document.getRootElement();
} else {
element = (Element) document.selectSingleNode(node);
}
return xmlToJson(element, result);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* XML文件转换对象
*
* @param xmlString xml字符串
* @return 对象
*/
public static List<XygMqStorage> xmlToObject(String xmlString) {
cn.hutool.json.JSONObject json = XML.toJSONObject(xmlString);
String parkId = json.getJSONObject("Message").getJSONObject("Body").getStr("ORGANIZATIONID");
Object obj = json.getJSONObject("Message").getJSONObject("Body").getJSONObject("REMAINLIST").getObj("REMAIN");
List<XygMqStorage> xygMqStorages = new ArrayList<>();
if (obj instanceof cn.hutool.json.JSONObject){
cn.hutool.json.JSONObject jsonObject = (cn.hutool.json.JSONObject) obj;
XygMqStorage xygMqStorage = com.alibaba.fastjson2.JSONObject.parseObject(jsonObject.toString(), XygMqStorage.class);
xygMqStorages.add(xygMqStorage);
}
if (obj instanceof cn.hutool.json.JSONArray ){
cn.hutool.json.JSONArray jsonObject = (cn.hutool.json.JSONArray) obj;
xygMqStorages = jsonObject.toList(XygMqStorage.class);
}
xygMqStorages.forEach(e->{
e.setCreationDate(new Date());
e.setParkId(parkId);
});
return xygMqStorages;
}
/**
* 生成xml格式的字符串
*
* @return
*/
public static String createXmlString(XmlParam xmlParam) {
//创建document对象
org.dom4j.Document document = DocumentHelper.createDocument();
//设置编码
document.setXMLEncoding("UTF-8");
//创建根节点
Element message = document.addElement("Message");
// 开始组装 Header 节点
// 在 Header 节点下加入子节点
Element header = message.addElement("Header");
// 组装固定值
for (HeaderEnum h : HeaderEnum.values()) {
Element childNode = header.addElement(h.name());
childNode.setText(h.getValue());
}
// 组装传参值
Map<String, String> headerMap = JSONObject.parseObject(JSONObject.toJSONString(xmlParam.getHeader()), Map.class);
headerMap.forEach((k, v) -> {
Element childNode = header.addElement(k.toUpperCase());
childNode.setText(v);
});
// 组装事务ID,唯一值:当前时间戳
Element transactionId = header.addElement("TRANSACTIONID");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String s = String.valueOf(Calendar.getInstance().getTimeInMillis());
transactionId.setText(sdf.format(new Date()) +s.substring(s.length()-4));
Element listener = header.addElement("listener");
listener.setText("QueueListener");
// 开始组装 Body 节点
Element body = message.addElement("Body");
Map<String, String> bodyMap = JSONObject.parseObject(JSONObject.toJSONString(xmlParam.getBody()), Map.class);
bodyMap.forEach((k, v) -> {
if (Objects.isNull(v)) {
return;
}
Element childNode = body.addElement(k.toUpperCase());
childNode.setText(v);
});
//将document对象转换成字符串
String xml = document.asXML();
// 去掉 XML 声明
if (xml.startsWith("<?xml")) {
xml = xml.substring(xml.indexOf(">") + 1);
}
return xml;
}
}
8.zip工具类
package com.xhao.common.util;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
@Slf4j
public class ZipUtil {
private static final int BUFFER_SIZE = 2 * 1024;
private static final int buffer = 2048;
public static void zip(String souceFileName, String destFileName) {
File file = new File(souceFileName);
try {
zip(file, destFileName);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 压缩成ZIP 方法2
*
* @param srcFiles 需要压缩的文件列表
* @param out 压缩文件输出流
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(List<File> srcFiles, OutputStream out) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void toSetZip(Set<File> srcFiles, OutputStream out) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void zip(File souceFile, String destFileName) throws IOException {
FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream(destFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ZipOutputStream out = new ZipOutputStream(fileOut);
zip(souceFile, out, "");
out.close();
}
public static void zip(File souceFile, ZipOutputStream out, String base)
throws IOException {
if (souceFile.isDirectory()) {
File[] files = souceFile.listFiles();
out.putNextEntry(new ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (File file : files) {
zip(file, out, base + file.getName());
}
} else {
if (base.length() > 0) {
out.putNextEntry(new ZipEntry(base));
} else {
out.putNextEntry(new ZipEntry(souceFile.getName()));
}
FileInputStream in = new FileInputStream(souceFile);
int b;
byte[] by = new byte[1024];
while ((b = in.read(by)) != -1) {
out.write(by, 0, b);
}
in.close();
}
}
/**
* 解压Zip文件
* 多目录
*
* @param
*/
public static String unZip(String path) {
int count = -1;
String savepath = "";
String filename = "";
File file = null;
InputStream is = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
//保存解压文件目录
savepath = path.substring(0, path.lastIndexOf(".")) + "/";
//创建保存目录
new File(savepath).mkdir();
ZipFile zipFile = null;
try {
//解决中文乱码问题
zipFile = new ZipFile(path, Charset.forName("gbk"));
Enumeration<?> entries = zipFile.entries();
long start = System.currentTimeMillis();
while (entries.hasMoreElements()) {
byte[] buf = new byte[buffer];
ZipEntry entry = (ZipEntry) entries.nextElement();
filename = entry.getName();
boolean ismkdir = false;
int lastIndex1 = filename.lastIndexOf("\\") == -1 ? filename.lastIndexOf("/") : filename.lastIndexOf("\\");
if (lastIndex1 != -1) {
// 检查此文件是否带有文件夹
ismkdir = true;
}
filename = savepath + filename;
if (entry.isDirectory()) { //如果是文件夹先创建
file = new File(filename);
file.mkdirs();
continue;
}
file = new File(filename);
if (!file.exists()) { //如果是目录先创建
if (ismkdir) {
int lastIndex2 = filename.lastIndexOf("\\") == -1 ? filename.lastIndexOf("/") : filename.lastIndexOf("\\");
new File(filename.substring(0, lastIndex2)).mkdirs(); //目录先创建
}
}
file.createNewFile(); //创建文件
is = zipFile.getInputStream(entry);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos, buffer);
while ((count = is.read(buf)) > -1) {
bos.write(buf, 0, count);
}
bos.flush();
bos.close();
fos.close();
is.close();
}
zipFile.close();
delZipFile(path);
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (bos != null) {
bos.close();
}
if (fos != null) {
fos.close();
}
if (is != null) {
is.close();
}
if (zipFile != null) {
zipFile.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
int lastIndex3 = 0;
if (System.getProperty("os.name").toLowerCase().indexOf("linux") >= 0) {
lastIndex3 = filename.lastIndexOf("\\");
} else {
lastIndex3 = filename.lastIndexOf("/");
}
return savepath;
}
// 删除zip 文件
public static void delZipFile(String url) {
File file = new File(url);
log.info("文件路径{}", url);
log.info("文件删除判断查询{}", file.exists());
if (file.exists()) {
if (file.getName().endsWith(".zip")) { // zip文件 判断 是否存在
if (file.delete()) {
log.info("zip文件已经删除");
} else {
log.info("zip文件删除失败");
}
}
}
}
public static List<String> getFile(String path, List<String> list) {
// 获得指定文件对象
File file = new File(path);
// 获得该文件夹内的所有文件
File[] array = file.listFiles();
for (int i = 0; i < array.length; i++) {
if (array[i].isFile()) {//如果是文件
list.add(array[i].toString());
} else if (array[i].isDirectory()) {//如果是文件夹
getFile(array[i].getPath(), list);
}
}
return list;
}
}
后续持续补充
如果点赞多,评论多会更新详细教程,待补充。