对字符串 String 的一些操作,String的一些常用方法
package com.es.util;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfDocument;
import com.itextpdf.text.pdf.PdfImage;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.interfaces.PdfVersion;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.management.Query;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLEncoder;
import java.text.*;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.sun.webkit.network.URLs.newURL;
/**
* <p>
*用于对字符串的修改
* </p>
*
* @Author: fxp
* @Date: 2021/4/10 10:56
*/
public class MyStringUtil {
/**
* 手机号 正则
*/
public static Pattern pattern = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
// 大于等于0的数
// public static final Pattern correctAmountRegular = Pattern.compile("^([0-9]+)(.[0-9]+)?$");
/**
* 大于 0 正则
*/
public static final Pattern correctAmountRegular = Pattern.compile("^(0\\.[1-9]\\d*|[1-9]\\d*(\\.\\d+)?)$");
/**
*
* 去掉最后一次出现的指定字符串,传入数据为null返回""
* 用于去除管家名字后的"已停用"
*
* @param yuan 原本的字符串
* @param zhiding 要去除的字符串
* @return
*/
public static String delEndFindString(String yuan,String zhiding){
if (null == yuan || null == zhiding){
return yuan;
}
int n = yuan.lastIndexOf(zhiding);
if (n == -1){
return yuan;
}
int i = yuan.length();
if (i == 0){
return yuan;
}
if (n == i-zhiding.length()){
yuan = yuan.substring(0,n);
}
return yuan;
}
/**
* @Author: fengxueping
* @date: 2021/4/27
* @MethodNotes: 判断长度大于多少,从多少位截断,后面加上什么符号
* @param: str:需要改变的字符串
* max:判断的长度大小依据
* n:从第几位开始截断
* s:要添加的字符串
* @return: 修改后的字符串
*/
public static String updateStringByLength(String str,Integer max,Integer n,String s){
if (str.length() > max){
str = str.substring(0,n);
str = str + s;
}
return str;
}
/**
* @Author: fengxueping
* @date: 2021/4/27
* @MethodNotes: 集合去重
* @param:
* @return:
*/
public static List<String> setDeduplication(List<String> l){
ArrayList<String> objects = new ArrayList<>();
LinkedHashSet<String> objects1 = new LinkedHashSet<>();
objects1.addAll(l);
objects.addAll(objects1);
return objects;
}
/**
* @Author: fengxueping
* @date: 2021/4/27
* @MethodNotes: 字符串转时间 yyyy-MM-dd
* @param:
* @return:
*/
public static Date stringToDate(String str) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = simpleDateFormat.parse(str);
return date;
}
public static Date stringToTime(String str) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = simpleDateFormat.parse(str);
return date;
}
public static Date stringNumToDate(String str) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
Date date = simpleDateFormat.parse(str);
return date;
}
/**
* @Author: fengxueping
* @date: 2021/5/13
* @MethodNotes: 获取当前时间字符串
* @param:
* @return:
*/
public static String getNewDate(){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String date = simpleDateFormat.format(new Date());
return date;
}
/**
* @Author: fengxueping
* @date: 2021/5/13
* @MethodNotes: Date转String
* @param:
* @return:
*/
public static String dateToString(Date date){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String s = simpleDateFormat.format(date);
return s;
}
public static String dateToStringStart(Date date){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
String s = simpleDateFormat.format(date);
return s;
}
public static String dateToStringEnd(Date date){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
String s = simpleDateFormat.format(date);
return s;
}
public static String timeToString(Date date){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = simpleDateFormat.format(date);
return s;
}
/**
* @Author: fengxueping
* @date: 2021/4/28
* @MethodNotes: 通过输入时间天数,和默认开始时间,得出结束时间
* @param:
* @return:
*/
public static String getEndTimeToInput(String start, Double day) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
int i = Double.hashCode(day * 1000 * 60 * 60 * 24);
Date s = stringToDate(start);
String e = df.format(stringToDate(start).getTime() + i);
return e;
}
/**
* 两个时间之间相差距离多少天
* @param str1 时间参数 1:
* @param str2 时间参数 2:
* @return 相差天数
*/
public static long getDistanceDays(String str1, String str2) throws Exception{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date one;
Date two;
long days=0;
try {
one = df.parse(str1);
two = df.parse(str2);
long time1 = one.getTime();
long time2 = two.getTime();
long diff ;
if(time1<time2) {
diff = time2 - time1;
} else {
diff = time1 - time2;
}
days = diff / (1000 * 60 * 60 * 24);
} catch (ParseException e) {
e.printStackTrace();
}
return days;
}
/**
* 两个时间之间相差距离多少天
* @param str1 时间参数 1:
* @param str2 时间参数 2:
* @return 相差天数
*/
public static long getDistanceDays(Date str1, Date str2) throws Exception{
Date one = str1;
Date two = str2;
long days=0;
long time1 = one.getTime();
long time2 = two.getTime();
long diff ;
if(time1<time2) {
diff = time2 - time1;
} else {
diff = time1 - time2;
}
days = diff / (1000 * 60 * 60 * 24);
return days;
}
/**
*
* @param type 返回时间的类型,0,年 1,月 2,日
* @param date1 比较时间1
* @param date2 比较时间2
* @return 时间差
*/
public static Integer dateDiff(Integer type,Date date1, Date date2){
long time1 = date1.getTime();
long time2 = date2.getTime();
long diff;
Integer days=0;
diff = time2 - time1;
switch (type){
case 2:
days = Math.toIntExact(diff / (1000 * 60 * 60 * 24));
break;
case 1:
days = getMonth(date1) - getMonth(date2);
break;
case 0:
days = getYear(date1) - getYear(date2);
break;
}
return days;
}
/**
* 获取日期中的年份
* @param day 日期
* @return 年,数字
*/
public static Integer getYear(Date day){
Calendar c = Calendar.getInstance();
c.setTime(day);
int year = c.get(Calendar.YEAR);
return year;
}
/**
* 获取日期中的月份
* @param day 日期
* @return 月,数字
*/
public static Integer getMonth(Date day){
Calendar c = Calendar.getInstance();
c.setTime(day);
int month = c.get(Calendar.MONTH) + 1;
return month;
}
/**
* 获取日期中的日期
* @param day 日期
* @return 日,数字
*/
public static Integer getDay(Date day){
Calendar c = Calendar.getInstance();
c.setTime(day);
int d = c.get(Calendar.DATE);
return d;
}
/**
* 增加日期,正数增加,负数减少
* @param date 指定的日期
* @param day 增加或减少的天数
* @param type 0年,1月,2日
* @return 新的日期
*/
public static Date addDay(Date date,Integer day,Integer type){
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
switch (type){
case 0:
calendar.add(Calendar.YEAR,day);
break;
case 1:
calendar.add(Calendar.MONTH,day);
break;
case 2:
calendar.add(Calendar.DATE,day);
break;
}
date=calendar.getTime();
return date;
}
/**
* 增加日期,正数增加,负数减少
* @param date 指定的日期
* @param day 增加或减少的天数
* @param type y年,m月,d日,hour时
* @return 新的日期
*/
public static Date addDay(String type,Integer day,Date date){
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
switch (type){
case "y":
calendar.add(Calendar.YEAR,day);
break;
case "m":
calendar.add(Calendar.MONTH,day);
break;
case "d":
calendar.add(Calendar.DATE,day);
break;
case "hour":
calendar.add(Calendar.HOUR,day);
break;
}
date=calendar.getTime();
return date;
}
/**
* 将年、月、日拼凑成一个日期
* @param year 年
* @param month 月
* @param day 日
* @return 新的日期
*/
public static Date splicingYearAndMonthAndDay(Integer year,Integer month,Integer day) throws ParseException {
while (month <= 0 || month > 12 || day <= 0 || day > 28){
if (month <= 0){
month = 1;
}
if (month > 12){
year = year + 1;
month = month - 12;
}
if (day <= 0){
day = 1;
}
Date date = stringToDate(year + "-" + month + "-" + "1");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Integer actualMaximum = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
if (day > actualMaximum){
day = day - actualMaximum;
month = month + 1;
continue;
}
break;
}
return stringToDate(year + "-" + month + "-" + day);
}
/**
* 是否为一个有效日期,通过转Date实现
* @param str
* @return
*/
public static boolean isValidDate(String str) {
boolean convertSuccess=true;
//指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
// 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
format.setLenient(false);
format.parse(str);
} catch (ParseException e) {
// e.printStackTrace();
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
convertSuccess=false;
}
return convertSuccess;
}
/**
* 判断是不是一个时间字符串
* @param strDate
* @return
*/
public static boolean isDate(String strDate) {
Matcher m = pattern.matcher(strDate);
if (m.matches()) {
if (strDate.split("-").length == 3){
return true;
}else {
return false;
}
} else {
return false;
}
}
/**
* 截取的串最后的文件名称和后缀名
* @param Str 截取的串
* @return
* 列子:
* D:\esfiles\三表抄表批量导入1625211690794.xlsx
* 截取后
* 三表抄表批量导入1625211690794.xlsx
*/
public static String getFileName(String Str) {
int pos = Str.lastIndexOf("/");
String extName = Str.substring(pos + 1);
return extName;
}
/**
* 获得 队列名称字符串
* @param queueNameModel
* @param num
* @param date
* @param numbering
* @return
* @throws Exception
*/
public static String getQueueName(String queueNameModel,Integer num,Date date,Integer numbering) throws Exception {
String[] strings = new String[]{num + "",MyStringUtil.getYear(date) + "",MyStringUtil.getMonth(date) + "",MyStringUtil.getDay(date) + "",getThreeDigitNumber(numbering)};
return MyStringUtil.solveQueueName(queueNameModel,strings);
}
/**
* 获得 队列名称字符串
* @param queueNameModel
* @param ss
* @param date
* @param numbering
* @return
* @throws Exception
*/
public static String getQueueName2(String queueNameModel,Date date,Integer numbering,String ...ss) throws Exception {
List<String> list = new ArrayList<>();
for (String s : ss) {
list.add(s);
}
list.addAll(getDateStrList(date));
list.add(numbering + "");
return MyStringUtil.solveQueueName(queueNameModel,list);
}
/**
*替换()中的内容
* @throws Exception
*/
public static String solveQueueName(String queueNameModel,String[] strings) throws Exception { // 处理函数
int i = 0;
String pattern = "\\([^)]*\\)"; // 匹配{} 的表达式
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(queueNameModel);
while(m.find()){ // 当字符串中有匹配到 {} 时
if (i == strings.length){
break;
}
String param = m.group(0); // {} 和里面的内容
//System.out.println(param.substring(1,param.length()-1)); // 输出{} 里面的内容
queueNameModel = queueNameModel.replaceFirst("\\([^)]*\\)",strings[i]); // 替换 {} 和里面的内容
i++;
}
return queueNameModel;
}
/**
*替换()中的内容
* @throws Exception
*/
public static String solveQueueName(String template,List<String> strings){
int i = 0;
String pattern = "\\([^)]*\\)";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(template);
while(m.find()){
if (i == strings.size()){
break;
}
template = template.replaceFirst("\\([^)]*\\)",strings.get(i));
i++;
}
return template;
}
/**
*替换括号中的内容,用于保存参数
*/
public static String solveQueueName(String queueNameModel,String pattern,List<String> strings){
int i = 0;
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(queueNameModel);
while(m.find()){
String param = m.group(0);
if (strings.size()==i){
return queueNameModel;
}
queueNameModel = queueNameModel.replaceFirst(pattern,"{"+strings.get(i)+"}");
i++;
}
return queueNameModel;
}
/**
*取出括号中的内容
*/
public static List<String> solveQueueName(String queueNameModel,String pattern){
int i = 0;
List<String> ss = new ArrayList<>();
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(queueNameModel);
while(m.find()){
String param = m.group(0);
ss.add(param.substring(1,param.length()-1));
i++;
}
return ss;
}
/**
*取出括号中的内容
*/
public static List<String> solveQueueName(String queueNameModel){
int i = 0;
String pattern = "\\{[^}]*\\}";
List<String> ss = new ArrayList<>();
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(queueNameModel);
while(m.find()){
String param = m.group(0);
ss.add(param.substring(1,param.length()-1));
i++;
}
return ss;
}
/**
* 转为三位数
* @param num
* @return
*/
public static String getThreeDigitNumber(Integer num){
if(num < 10){
return "00" + num;
}else if (num < 100){
return "0" + num;
}else {
return num + "";
}
}
/**
* 获取时间的,年月日字符串集合
* @param date
* @return
*/
public static List<String> getDateStrList(Date date){
List<String> ss = new ArrayList<>();
Calendar c = Calendar.getInstance();
c.setTime(date);
int year = c.get(Calendar.YEAR);
ss.add(c.get(Calendar.YEAR) + "");
ss.add((c.get(Calendar.MONTH) + 1) + "");
ss.add(c.get(Calendar.DATE) + "");
return ss;
}
/**
* 获取时间的,年月日数字
* @param date
* @return
*/
public static String getDateStrNum(Date date){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
String s = simpleDateFormat.format(date);
return s;
}
/**
* 金额验证
* @param s
* @return
*/
public static Boolean correctAmount(String s){
Matcher m = correctAmountRegular.matcher(s);
return m.matches();
}
/**
* 判读是不是null或空
* @param s
* @return
*/
public static Boolean isNullOrEmpty(String s){
if (null == s || "".equals(s)){
return true;
}else {
return false;
}
}
/**
* 判读是不是null或空
* @param s
* @return
*/
public static String isNullOrEmptyReturnStr(String s){
if (null == s || "".equals(s)){
return "";
}else {
return s;
}
}
/**
* 将八位数字字符串,转为字符串
* @param s8
* @return
*/
public static String getDateStringTo8String(String s8) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
Date date = simpleDateFormat.parse(s8);
return dateToString(date);
}
/**
* 收费来源
* @throws Exception
*/
public static String getSourceOfCharges(String s){
switch (s){
case "-1":
return "导入";
case "0":
return "前台";
case "1":
return "自助";
case "2":
return "退款";
case "3":
return "银行托收";
case "4":
return "批量划账";
case "5":
return "批量打票";
case "6":
return "预付款互转";
default:
return "其他";
}
}
/**
* 判断后者时间是否在前者时间之前,第一个时间是否比第二个大
* @throws Exception
*/
public static Boolean isForwardByDate(Date date1,Date date2){
long days=0;
long time1 = date1.getTime();
long time2 = date2.getTime();
long diff ;
diff = time1 - time2;
days = diff / (1000 * 60 * 60 * 24);
return days>0;
}
public static Boolean isForwardByDate(String date1,String date2) throws ParseException {
long days=0;
long time1 = stringToDate(date1).getTime();
long time2 = stringToDate(date2).getTime();
long diff ;
diff = time1 - time2;
days = diff / (1000 * 60 * 60 * 24);
return days>=0;
}
public static Boolean isForwardByDateN(String date1,String date2) throws ParseException {
long days=0;
long time1 = stringToDate(date1).getTime();
long time2 = stringToDate(date2).getTime();
long diff ;
diff = time1 - time2;
days = diff / (1000 * 60 * 60 * 24);
return days>0;
}
public static String getTypeStr(String typeInt) {
// 审批状态 1对账中 2提交失败 3待提交 4未审批 5打回 6审批通过 -1作废
switch (typeInt){
case "-1":
return "已作废";
case "1":
return "对账中";
case "2":
return "提交失败";
case "3":
return "未提交";
case "4":
return "未审批";
case "5":
return "已打回";
case "6":
return "审批通过";
default:
return "其他";
}
}
/**
* c从第几位开始, 取几位 下标开始为1
* @param str 原字符串
* @param begin 开始下标
* @param num 取几位
* @return 截取后字符串
*/
public static String mySubString(String str,Integer begin,Integer num){
Integer end = 0;
Integer start = 0;
if (begin<0){
start = 0;
}else if (begin > str.length()){
start = str.length();
}else {
start = begin-1;
}
if (begin+num-1 > str.length()){
end = str.length();
}else {
end = begin+num-1;
}
return str.substring(start,end);
}
/**
* 截取倒数几位
* @param str 原字符串
* @param num 倒数的位数
* @return 截取后的字符串
*/
public static String myRight(String str,Integer num){
if (num > str.length()){
return str;
}
return str.substring(str.length() - num,str.length());
}
/**
* 按天拆分时间段
*/
public static List<String> splitTime(Date s,Date e) throws Exception {
List<String> ss = new ArrayList<>();
ss.add(dateToString(s));
Integer integer = dateDiff(2, s, e);
for (int i = 0; i < integer; i++) {
Date d = addDay("d",1,s);
ss.add(dateToString(d));
s = d;
}
return ss;
}
/**
* <p>将文件转成base64 字符串</p>
* @param path 文件路径
*/
public static String encodeBase64File(String path) throws Exception {
File file = new File(path);
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int)file.length()];
inputFile.read(buffer);
inputFile.close();
return new BASE64Encoder().encode(buffer);
}
/**
* <p>将文件转成base64 字符串</p>
* @param file 文件
*/
public static String encodeBase64File(File file) throws Exception {
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int)file.length()];
inputFile.read(buffer);
inputFile.close();
return new BASE64Encoder().encode(buffer);
}
/**
* <p>将base64字符解码保存文件</p>
*/
public static void decoderBase64File(String base64Code,String targetPath) throws Exception {
byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
FileOutputStream out = new FileOutputStream(targetPath);
out.write(buffer);
out.close();
}
/**
* <p>将base64字符保存文本文件</p>
*/
public static void toFile(String base64Code,String targetPath) throws Exception {
byte[] buffer = base64Code.getBytes();
FileOutputStream out = new FileOutputStream(targetPath);
out.write(buffer);
out.close();
}
/**
* 删除指定文件
* @param file
*/
private static void deleteDirectory(File file) {
if (file.isFile()) {// 表示该文件不是文件夹
file.delete();
} else {
// 首先得到当前的路径
String[] childFilePaths = file.list();
for (String childFilePath : childFilePaths) {
File childFile = new File(file.getAbsolutePath() + "/" + childFilePath);
deleteDirectory(childFile);
}
file.delete();
}
}
/**
* 删除指定文件
* @param file
*/
public static void deleteFile(File file){
if(file.exists() && file.isFile()){
file.delete();
}
}
/**
* 浏览器导出二维码
* @param filename
* @param response
* @param bufImg
* @throws Exception
*/
public static void download(String filename,HttpServletResponse response,BufferedImage bufImg) throws Exception {
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Document document = new Document(PageSize.A4);
// PdfWriter writer = PdfWriter.getInstance(document, baos);
// document.setMargins(64, 64, 36, 36);
// document.open();
// ImageIO.write(bufImg, "png", baos);
// Image image = Image.getInstance(baos.toByteArray());
// document.add(image);
// document.close();
//判断浏览器代理并分别设置响应给浏览器的编码格式
String finalFileName = null;
finalFileName = URLEncoder.encode(filename+".png","UTF8");
//设置HTTP响应头
//重置 响应头
response.reset();
//告知浏览器下载文件,而不是直接打开,浏览器默认为打开
response.setContentType("image/png");
// response.setContentType("application/octet-stream;charset=utf-8");
// response.setHeader("Content-Type", "application/pdf");
// response.setContentType("application/pdf");
// response.setContentType("application/pdf");
//下载文件的名称
// response.addHeader("Content-Disposition" ,"attachment;filename=\"" +finalFileName+ "\""+".jpg");
// response.setHeader("Content-Disposition", "attachment;filename="
// + finalFileName + ".png");
response.setHeader("Content-disposition", "attachment;filename="+finalFileName+"filename*=utf-8''"+finalFileName + ".png");
// response.setHeader("Content-Disposition", "attachment;filename=" + new String(finalFileName.getBytes("gb2312"), "ISO8859-1"));
// response.setContentLength(baos.size());
// OutputStream out = response.getOutputStream();
// baos.writeTo(out);
// out.flush();
// out.close();
// BufferedInputStream input = new BufferedInputStream(new ByteArrayInputStream(document));
// 输入流
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufImg, "png", os);
InputStream inStream = new ByteArrayInputStream(os.toByteArray());
// 循环取出流中的数据
byte[] b = new byte[1024];
int len;
while ((len = inStream.read(b)) > 0){
response.getOutputStream().write(b, 0, len);
}
inStream.close();
response.getOutputStream().close();
}
/**
* 等比压缩,获取压缩百分比
*
* @param height 图片的高度
* @param weight 图片的宽度
* @return 压缩百分比
*/
private static int getPercent(float height, float weight) {
float percent = 0.0F;
if (height > weight) {
percent = PageSize.A4.getHeight() / height * 100;
} else {
percent = PageSize.A4.getWidth() / weight * 100;
}
return Math.round(percent);
}
/**
* 获取当前机器端口号
*
*/
public static String getLocalPort() throws Exception {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> objectNames = mBeanServer.queryNames(new ObjectName("*:type=Connector,*"), null);
if (objectNames == null || objectNames.size() <= 0) {
throw new IllegalStateException("Cannot get the names of MBeans controlled by the MBean server.");
}
for (ObjectName objectName : objectNames) {
String protocol = String.valueOf(mBeanServer.getAttribute(objectName, "protocol"));
String port = String.valueOf(mBeanServer.getAttribute(objectName, "port"));
// windows下属性名称为HTTP/1.1, linux下为org.apache.coyote.http11.Http11NioProtocol
if (protocol.equals("HTTP/1.1") || protocol.equals("org.apache.coyote.http11.Http11NioProtocol")) {
return port;
}
}
throw new IllegalStateException("Failed to get the HTTP port of the current server");
}
/**
* 获取当前机器的IP
*
*/
public static String getLocalIP() throws Exception {
InetAddress addr = InetAddress.getLocalHost();
byte[] ipAddr = addr.getAddress();
String ipAddrStr = "";
for (int i = 0; i < ipAddr.length; i++) {
if (i > 0) {
ipAddrStr += ".";
}
ipAddrStr += ipAddr[i] & 0xFF;
}
return ipAddrStr;
}
/**
* 获取端口号
* @return
*/
public static String getLocalPort2() {
try {
MBeanServer server;
if (MBeanServerFactory.findMBeanServer(null).size() > 0) {
server = MBeanServerFactory.findMBeanServer(null).get(0);
} else {
return "";
}
Set<ObjectName> names = server.queryNames(new ObjectName("Catalina:type=Connector,*"),
Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
Iterator<ObjectName> iterator = names.iterator();
if (iterator.hasNext()) {
ObjectName name = iterator.next();
return server.getAttribute(name, "port").toString();
}
}
catch (Exception e) {
// LoggerUtil.log(Level.INFO, "获取port出现异常:{}", e.getMessage());
}
return "";
}
/**
* http 加号乱码
* @param
* @return
*/
// public static String acceptSalesOrder(Dictionary<String, Object> dicpostData)
// {
// String jsontoken =XT.Utility.EncryptObject.UnicodeToGB(JSONHelper.ToJson(dicpostData));
// String md5token = XT.Utility.EncryptObject.GetMD5(token + jsontoken);
// String jsontokenj = jsontoken.Replace("+", "%2B");
// String postData = "&token=" + md5token + "&postData=" + jsontokenj;
// String strUrl = "acceptSalesOrder.pub";
// String htmlUrl = string.Format("{0}{1}", url, strUrl);
// return Web_Request.POST_WebRequestHTML(encodingName, htmlUrl, postData);
// }
public static boolean isNumeric3(String str) {
if (str == null || "".equals(str)){return false;}
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
return str.length() == pos.getIndex();
}
private static final Pattern NUMBER_PATTERN = Pattern.compile("-?\\d+(\\.\\d+)?");
public static boolean isNumeric2(String str) {
return str != null && NUMBER_PATTERN.matcher(str).matches();
}
public static String parseNumber(String bd) {
if (null == bd || "".equals(bd)){
return "";
}
if (isNumeric2(bd)){
DecimalFormat df = new DecimalFormat(",###,##0.00");
return df.format(new BigDecimal(bd));
}
return bd;
}
/**
* 保留两位小数
* @param bd
* @return
*/
public static BigDecimal parseBigDecimalNumber(BigDecimal bd) {
if (isNumeric2(bd.toString())){
DecimalFormat df = new DecimalFormat("0.00#");
return new BigDecimal(df.format(bd));
}
return bd;
}
public static String parseNumberToTenThousand(String bd) {
if (null == bd || "".equals(bd)){
return "";
}
if (isNumeric2(bd)){
BigDecimal bigDecimal = new BigDecimal(bd);
BigDecimal divide = bigDecimal.divide(new BigDecimal("10000"), 6, BigDecimal.ROUND_HALF_UP);
return parseNumber(divide.toString());
}
return bd;
}
/**
* 获取系统时间,当月的第一天
* @return
*/
public static Date firstByMonth(){
//获取当前日期
Calendar cal_1=Calendar.getInstance();
cal_1.add(Calendar.MONTH, 0);
//设置为1号,当前日期既为本月第一天
cal_1.set(Calendar.DAY_OF_MONTH,1);
return cal_1.getTime();
}
/**
* 获取一个正确时间
* @param year
* @param month
* @param day
* @return
* @throws ParseException
*/
public static String getCorrectDay(Integer year,Integer month,String day) throws ParseException {
String monthLastDay = getMonthLastDay2(year + "-" + month + "-01");
String[] split = monthLastDay.split("-");
Integer integer = Integer.valueOf(split[2]);
Integer integer1 = Integer.valueOf(day);
if (integer1 >= integer){
return integer+"";
}else {
return integer1+"";
}
}
/**
* 获取传入时间,当月的第一天
* @return
*/
public static Date firstByMonth(Date date){
//获取当前日期
Calendar cal_1=Calendar.getInstance();
cal_1.setTime(date);
cal_1.add(Calendar.MONTH, 0);
//设置为1号,当前日期既为本月第一天
cal_1.set(Calendar.DAY_OF_MONTH,1);
return cal_1.getTime();
}
/**
* 获取时间,高级
* @param date
* @param type 1 当月第几天 2 当年第几天 -1 当月最后几天 -2 当年最后几天
* @return
*/
public static Date getDateByType(Date date,Integer type,Integer day){
//获取当前日期
Calendar cal_1=Calendar.getInstance();
cal_1.setTime(date);
switch (type){
case 1:
cal_1.add(Calendar.MONTH, 0);
//设置为1号,当前日期既为本月第一天
cal_1.set(Calendar.DAY_OF_MONTH,day);
break;
case 2:
cal_1.add(Calendar.YEAR, 0);
cal_1.set(Calendar.DAY_OF_YEAR,day);
break;
case -1:
cal_1.add(Calendar.MONTH, 1);
cal_1.set(Calendar.DAY_OF_MONTH,-1*day+1);
break;
case -2:
cal_1.add(Calendar.YEAR, 1);
cal_1.set(Calendar.DAY_OF_YEAR,-1*day+1);
break;
default:
break;
}
return cal_1.getTime();
}
/**
* 获取月的最后一天
* @return
*/
public static String getMonthLastDay(String date) throws ParseException {
Calendar calendar = Calendar.getInstance();
calendar.setTime(stringToDate(date));
calendar.set(Calendar.DAY_OF_MONTH,0);
calendar.add(Calendar.MONTH,1);
return dateToStringEnd(calendar.getTime());
}
/**
* 获取月的最后一天
* @return
*/
public static String getMonthLastDay2(String date) throws ParseException {
Calendar calendar = Calendar.getInstance();
calendar.setTime(stringToDate(date));
calendar.set(Calendar.DAY_OF_MONTH,0);
calendar.add(Calendar.MONTH,1);
return dateToString(calendar.getTime());
}
/**
* 获取月的最后一天
* @return
*/
public static Integer getMonthLastDay(Integer year,Integer month) throws ParseException {
Calendar calendar = Calendar.getInstance();
calendar.setTime(stringToDate(year+"-"+month+"-01"));
calendar.set(Calendar.DAY_OF_MONTH,0);
calendar.add(Calendar.MONTH,1);
return getDay(calendar.getTime());
}
public static String longTimeToString(Long time){
try {
return dateToString(new Date(time));
}catch (Exception e){
return "1900-01-01";
}finally {
}
}
/**
* BigDecimal 金额转换为千分位逗号分隔字符串
* @param amount (整数/小数)
* @return 字符串
*/
public static String convertThousand(BigDecimal amount){
String strAmt = amount.toString();
String[] split = strAmt.split("\\.");
List<String> list = new ArrayList<String>(Arrays.asList(split));
String one = list.get(0);
String two = "";
if (list.size() > 1) {
two = "."+list.get(1);
}
int i = Integer.parseInt(one);
DecimalFormat df = new DecimalFormat("#,###");
String format = df.format(i);
// 组装返回
return format = format + two;
}
/**
* 给类及其所有父类赋值
* @param object
*/
public static void converEmptyNullToString(Object object) {
try {
Class cl = object.getClass();
List<Field> fields = new ArrayList<>();
Object obj = object;
while (cl != null){
Field[] fs = obj.getClass().getDeclaredFields();
fields = new ArrayList<>(Arrays.asList(fs));
for (Field f : fields) {
f.setAccessible(true);
Object val = f.get(obj);
String type = f.getType().toString();
if (null == val){
if (type.endsWith("String")){
f.set(object,"");
}
if (type.endsWith("BigDecimal")){
f.set(object,BigDecimal.ZERO);
}
if (type.endsWith("Integer")){
f.set(object,0);
}
if (type.endsWith("Date")){
f.set(object,DateUtils.dateStrToDate("1900-01-01"));
}
}
}
cl = cl.getSuperclass();
if (null != cl){
obj = cl.newInstance();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}