commutils-程序员宅基地

技术标签: commutils  

package com.huawei.cloud.util.commonUtil;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.text.Collator;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


/**
* 公用方法
* @author mickey
*/
public class CommonUtil {

//一年中月的个数
private static final int MONTHS_OF_YEAR = 12;
//一年中日的个数
private static final int DAYS_OF_YEAR = 365;
//闰年中日的个数
private static final int DAYS_OF_SPECIAL_YEAR = 366;

//MD5编码字符常量
private final static String[] s_hexDigits={ "0", "1", "2", "3", "4",
"5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

/**
* 将对象转换成字符串<br>
* @param object 需转换的对象
* @return 转换出来的字符串
*/
public static String convertToString(Object object)
{
if(object==null || object.toString().equals("")){
return "";
}
//object是数字字符
if(object instanceof Number){
NumberFormat nf=NumberFormat.getInstance();
//禁止分组设置
nf.setGroupingUsed(false);
//小数点后精确到2位
nf.setMaximumFractionDigits(2);
return nf.format(object);
}
if(object instanceof Date) return convertDateTime((Date)object);
return object.toString();
}
/**
* 将数字对象转换成百分比字符串(小数点后精确到4位)
* 将非数字对象转换成空的字符串
* @param object 需转换的对象
* @return 转换出来的字符串
*/
public static String convertToPercent(Object object)
{
if(object==null){
return "";
}
//object是数字字符
if(object instanceof Number){
String numString = convertToString(object);
if(numString==null || numString.length()<1) return "";
try{
double value=Double.parseDouble(numString) * 100;
NumberFormat nf=NumberFormat.getInstance();
nf.setGroupingUsed(false);
nf.setMaximumFractionDigits(2);
StringBuffer percent=new StringBuffer();
percent.append(nf.format(value)).append("%");
return percent.toString();
}catch(NumberFormatException e){
return "";
}
}
return "";
}
/**
* 将日期对象按照默认日期格式(yyyy-mm-dd)转换成字符串(将空的对象转换成空的字符串)<br>
* @param date 需转换的日期对象
* @return 转换出来的字符串
*/
public static String convertDate(Date date)
{
if(date==null) return "";
return DateFormat.getDateInstance().format(date);
}
/**
* 将日期对象按照默认时间格式(hh:mm:ss)转换成字符串(将空的对象转换成空的字符串)<br>
* @param time 需转换的日期对象
* @return 转换出来的字符串
*/
public static String convertTime(Date time)
{
if(time==null) return "";
return DateFormat.getTimeInstance().format(time);
}
/**
* 将日期对象按照默认日期时间格式(yyyy-mm-dd hh:mm:ss)转换成字符串(将空的对象转换成空的字符串)<br>
* @param dateTime 需转换的日期对象
* @return 转换出来的字符串
*/
public static String convertDateTime(Date dateTime)
{
if(dateTime==null) return "";
return DateFormat.getDateTimeInstance().format(dateTime);
}
/**
* 将日期对象按照长格式(如:2007年12月5日 星期三)转换成字符串(将空的对象转换成空的字符串)
* @param date 需要转换的日期对象
* @return 转换出来的字符串
*/
public static String convertDateInLongMod(Date date)
{
if(date==null) return "";
Calendar calendar=Calendar.getInstance();
calendar.setTime(date);
int year=calendar.get(Calendar.YEAR);
int month=calendar.get(Calendar.MONTH);
int day=calendar.get(Calendar.DAY_OF_WEEK);
int weekday=calendar.get(Calendar.DAY_OF_WEEK);
StringBuffer dateString=new StringBuffer();
dateString.append(year);
dateString.append("年");
dateString.append(month+1);
dateString.append("月");
dateString.append(day);
dateString.append("日 星期");
switch(weekday)
{
case 1: {
dateString.append("日");
break;
}
case 2: {
dateString.append("一");
break;
}
case 3: {
dateString.append("二");
break;
}
case 4: {
dateString.append("三");
break;
}
case 5: {
dateString.append("四");
break;
}
case 6: {
dateString.append("五");
break;
}
case 7: {
dateString.append("六");
break;
}
}
return dateString.toString();
}
/**
* 获取日期对象的日期部分
* @param date 日期对象,默认为当前时间
* @return Date
*/
public static Date getDate(Date date)
{
if(date==null) date=new Date();
Calendar calendar=Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* 转换字节为10进制字符
* @param byte
* @return String
*/
public static String byteToNumString(byte b_bit)
{
int i_bit=b_bit;
if(i_bit<0){
i_bit=256+b_bit;
}
return String.valueOf(i_bit);
}
/**
* 转换字节为16进制字符
* @param byte
* @return String
*/
public static String byteToHexString(byte b_bit)
{
int i_bit=b_bit;
if(i_bit<0){
i_bit=256+b_bit;
}
int i_tempbit1=i_bit/16;
int i_tempbit2=i_bit%16;
return s_hexDigits[i_tempbit1]+s_hexDigits[i_tempbit2];
}
/**
* 转换字节数组为16进制字串
* @param b 字节数组
* @return 16进制字串
*/
public static String byteArrayToString(byte[] b) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
resultSb.append(byteToHexString(b[i]));//若使用本函数转换则可得到加密结果的16进制表示,即数字字母混合的形式
//resultSb.append(byteToNumString(b[i]));//使用本函数则返回加密结果的10进制数字字串,即全数字形式
}
return resultSb.toString();
}
/**
* 对字符串MD5加密
* @param s_origin准备Md5的字符串
* @return Md5加密后的字符串
*/
public static String Md5Encode(String s_origin)
{
String s_result=null;
try{
s_result=new String(s_origin);
MessageDigest md=MessageDigest.getInstance("MD5");
s_result=byteArrayToString(md.digest(s_result.getBytes()));
}catch(Exception e){
e.printStackTrace();
}
return s_result;
}
/**
* 将字符串转换为日期
* @param str
* @return Date
*/
public static Date convertStringtoDate(String str){
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date=new Date();
try {
date = format.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return date ;
}
/**
* 将字符串转换为日期时间
* @param str
* @return Date
*/
public static Date convertStringtoDateTime(String str){
DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");
Date date=null;
try {
date = format.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return date ;
}
/**
* 判断字符串是否为空
* @param str
* @return true/false
*/
public static boolean isNullString(String str)
{
return (str==null || str.trim().equals(""));
}
/**
* 判断列表是否为空
* @param list 源列表
* @author true/false
*/
public static boolean isNullList(List list)
{
return (list==null || list.isEmpty());
}
/**
* 判断Map是否为空
* @param map 源列表
* @author true/false
*/
public static boolean isNullMap(Map map)
{
return (map==null || map.isEmpty());
}
/**
* 将字符串转换为整型
* @param str
* @return int
*/
public static int stringToInt(String str) {
if (str == null||"".equals(str))
return 0;
return Integer.parseInt(str);
}
/**
* 将字符串转换为浮点数
* @param str
* @return float
*/
public static float stringToFloat(String str) {
if (str == null||"".equals(str))
return 0F;
return Float.parseFloat(str);
}
/**
* 获得上传文件的URL路径,并将文件传入指定路径
* @param f_file 上传的文件
* @param request
* @param s_path -> this.getServlet().getServletContext().getRealPath("/")
* @return
*/
// public static String getUpFileURL(FormFile f_file,HttpServletRequest request,String s_path)
// {
// Calendar cal=new GregorianCalendar();
//
// String s_name=f_file.getFileName().substring(f_file.getFileName().lastIndexOf("."));
//
// File tempfile=null;
// String fileurl=null;
// String date=null;
// String time=null;
// do{
// date=cal.get(Calendar.YEAR)+"_"+(cal.get(Calendar.MONTH)+1)+"_"+cal.get(Calendar.DATE);
// time=date+"-"+System.currentTimeMillis();
//
// fileurl=s_path+"upload/"+date+"/"+time+s_name;
// tempfile=new File(fileurl);
// }while(tempfile.exists());
//
// tempfile.getParentFile().mkdirs();
// writeToFile(fileurl, f_file);
//
// String path=request.getContextPath();
// String basepath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/upload/";
// String s_filename=basepath+date+"/"+time+s_name;
// return s_filename;
// }
// /**
// * 将指定文件写入到指定路径
// * @param fileurl
// * @param f_file
// * @return true/false
// */
// public static boolean writeToFile(String fileurl,FormFile f_file)
// {
// try{
// InputStream in_stream=f_file.getInputStream();
// File temfile=new File(fileurl);
// temfile.getParentFile().mkdirs();
//
// OutputStream out_stream=new FileOutputStream(fileurl);
// int bytesread=0;
// byte[] buffer=new byte[8192];
// while((bytesread=in_stream.read(buffer,0,8192))!=-1)
// {
// out_stream.write(buffer,0,bytesread);
// }
// out_stream.close();
// in_stream.close();
// return true;
// }catch(FileNotFoundException e){
// e.printStackTrace();
// return false;
// } catch (IOException e) {
// e.printStackTrace();
// return false;
// }
// }
/**
* 填充字符串
* @param source 源字符串
* @param fill 填充的字符串
* @param length 最终需要的字符串长度
* @return 填充后的字符串
*/
public static String fileString(String source,String fill,int length)
{
if(fill==null || fill.length()==0 || length<0) return source;
StringBuffer filledString = new StringBuffer();
if(source!=null) filledString.append(source);
int srcLength=0;
if(source!=null) srcLength=source.length();
if(srcLength<length)
{
//计算填充的次数
int fillTimes=(length-srcLength)/fill.length();
//计算剩余填充的长度
int spareLen=(length-srcLength)%fill.length();

for(int i=0;i<fillTimes;i++) filledString.append(fill);
if(spareLen>0) filledString.append(fill.substring(0, spareLen));
}
return filledString.toString().substring(0,length);
}
/**
* 获取Map排序后的键集的迭代器
* @param map 源Map(其中所有的键皆为字符串)
* @param numberKey 源Map中的键是否是数字(如:"1","2","3"等)
* @return 排序后的键集
*/
public static Iterator getSortedKeyIterator(Map map,boolean numberKey)
{
if(map==null || map.keySet()==null) return null;
try{
//将健集转换成列表
List keys=new ArrayList();
Iterator it=map.keySet().iterator();
while(it.hasNext()){
if(numberKey){
keys.add(new Long((String)it.next()));
}else{
keys.add((String)it.next());
}
}
//排序
if(numberKey){
Collections.sort(keys);
List tempkeys=new ArrayList();
for(int i=0;i<keys.size();i++)
{
tempkeys.add(convertToString(keys.get(i)));
}
return tempkeys.iterator();
}else{
Collections.sort(keys,Collator.getInstance());
return keys.iterator();
}
}catch(Exception e){
return map.keySet().iterator();
}
}
/**
* 将源字符串的首字母大写
* @param str
* @return
*/
public static String uppercaseInitiativeLetter(String str)
{
if(isNullString(str)) return "";
String initiativeLetter=str.trim().substring(0, 1).toUpperCase();
if(str.trim().length()==1) return initiativeLetter;
String otherStr=str.trim().substring(1);
return initiativeLetter+otherStr;
}
/**
* 按指定长度截取指定字符串
* @param str
* @param length
* @return
*/
public static String splitStringByLength(String str, int length)
{
return str.substring(0, length-1);
}

/**
* 将整数转换为字符串(汉字小写模式,例如:110--一百一十)
* @param num 目标整数
* @return
*/
public static String convertIntToStringInChineseLowMode(int num)
{
switch(num){
case 0: return "零";
case 1: return "一";
case 2: return "二";
case 3: return "三";
case 4: return "四";
case 5: return "五";
case 6: return "六";
case 7: return "七";
case 8: return "八";
case 9: return "九";
}
StringBuffer numString=new StringBuffer();
if(num<0){
num=num * -1;
numString.append("负");
}
//万位
int w=num/10000;
if(w>0){
numString.append(convertIntToStringInChineseLowMode(w)).append("万");
num=num%10000;
}
//千位
int q=num/1000;
if(q>0){
numString.append(convertIntToStringInChineseLowMode(q)).append("千");
num=num%1000;
}
//百位
int b=num/100;
if(b>0){
if(w > 0 && q == 0) numString.append("零");
numString.append(convertIntToStringInChineseLowMode(b)).append("百");
num=num%100;
}
//十位
int s = num / 10;
if(s > 0) {
if((w > 0 || q > 0) && b == 0) numString.append("零");
numString.append(convertIntToStringInChineseLowMode(s));
numString.append("十");
num = num % 10;
}
//个位
if(num > 0) {
if((w > 0 || q > 0 || b > 0) && s == 0) numString.append("零");
numString.append(convertIntToStringInChineseLowMode(num));
}

return numString.toString();
}
/**
* 将整数转换为字符串(汉字大写模式,例如:110--壹百壹拾)
* @param num 目标整数
* @return
*/
public static String convertIntToStringInChineseUppMode(int num) {
switch(num) {
case 0:return "零";
case 1:return "壹";
case 2:return "贰";
case 3:return "叁";
case 4:return "肆";
case 5:return "伍";
case 6:return "陆";
case 7:return "柒";
case 8:return "捌";
case 9:return "玖";
}

StringBuffer numString = new StringBuffer();
if(num < 0) {
num = num * -1;
numString.append("负");
}
//万位
int w = num / 10000;
if(w > 0) {
numString.append(convertIntToStringInChineseUppMode(w)).append("万");
num = num % 10000;
}
//千位
int q = num / 1000;
if(q > 0) {
numString.append(convertIntToStringInChineseUppMode(q)).append("仟");
num = num % 1000;
}
//百位
int b = num / 100;
if(b > 0) {
if(w > 0 && q == 0) numString.append("零");
numString.append(convertIntToStringInChineseUppMode(b)).append("佰");
num = num % 100;
}
//十位
int s = num / 10;
if(s > 0) {
if((w > 0 || q > 0) && b == 0) numString.append("零");
numString.append(convertIntToStringInChineseUppMode(s)).append("拾");
num = num % 10;
}
//个位
if(num > 0) {
if((w > 0 || q > 0 || b > 0) && s == 0) numString.append("零");
numString.append(convertIntToStringInChineseUppMode(num));
}

return numString.toString();
}
/**
* 判断是否是闰年
* @param year 年份
* @return true/false
*/
public static boolean isSpecialYear(int year)
{
if(year%4==0){
if(year%400==0) return true;
else if(year%100==0) return false;
else return true;
}else{
return false;
}
}
/**
* 按照范围要求把旧路径下大图变成小图存放到新路径下
* @param oldPath 旧路径
* @param newPath 新路径
* @param width 要求范围宽度
* @param height 要求范围长度
* @param b_keep 是否改变大小
* @throws IOException
*/
public static void changePicScale(String oldPath,String newPath,int width,int height,boolean b_keep) throws IOException
{
Image img=null;
File oldFile=new File(oldPath);
int i_width=1;
int i_height=1;
try{
img=javax.imageio.ImageIO.read(oldFile);
}catch(IOException e){
e.printStackTrace();
}
//等比例改变图片大小
if(b_keep)
{
int imgWidth=img.getWidth(null);
int imgHeight=img.getHeight(null);
float f_scale=(float)imgWidth/(float)imgHeight;
float scale=(float)width/(float)height;
if(f_scale<scale)
{
i_height=height;
i_width=(int)((float)i_height * f_scale);
}
else
{
i_width=width;
i_height=(int)((float)i_width / f_scale);
}
}
else
{
i_width=width;
i_height=height;
}
BufferedImage bfimg=new BufferedImage(i_width,i_height,BufferedImage.TYPE_INT_RGB);
Graphics g=bfimg.getGraphics();
g.drawImage(img, 0, 0, i_width, i_height, null);
g.dispose();
//创建新路径
File newFile=new File(newPath);
File newFileParent=newFile.getParentFile();
if(!newFileParent.exists()) newFileParent.mkdirs();
//保存图片
FileOutputStream outstream=new FileOutputStream(newPath);
JPEGImageEncoder j_encoder=JPEGCodec.createJPEGEncoder(outstream);
j_encoder.encode(bfimg);
outstream.close();
}
/**
* 字符串编码转换
* @param str
* @return
*/
public static String toTranslate(String str){
if(str==null || str.length()<1){
str="";
}
else{
try{
str=new String(str.getBytes("ISO8859-1"),"UTF-8");
str=str.trim();
}
catch(UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
e.printStackTrace();
return str;
}
}
return str;
}

}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/mickey_houzi/article/details/84116233

智能推荐

达梦数据库的导出(备份)、导入_达梦数据库导入导出-程序员宅基地

文章浏览阅读2.9k次,点赞3次,收藏10次。偶尔会用到,记录、分享。1. 数据库导出1.1 切换到dmdba用户su - dmdba1.2 进入达梦数据库安装路径的bin目录,执行导库操作  导出语句:./dexp cwy_init/[email protected]:5236 file=cwy_init.dmp log=cwy_init_exp.log 注释:   cwy_init/init_123..._达梦数据库导入导出

js引入kindeditor富文本编辑器的使用_kindeditor.js-程序员宅基地

文章浏览阅读1.9k次。1. 在官网上下载KindEditor文件,可以删掉不需要要到的jsp,asp,asp.net和php文件夹。接着把文件夹放到项目文件目录下。2. 修改html文件,在页面引入js文件:<script type="text/javascript" src="./kindeditor/kindeditor-all.js"></script><script type="text/javascript" src="./kindeditor/lang/zh-CN.js"_kindeditor.js

STM32学习过程记录11——基于STM32G431CBU6硬件SPI+DMA的高效WS2812B控制方法-程序员宅基地

文章浏览阅读2.3k次,点赞6次,收藏14次。SPI的详情简介不必赘述。假设我们通过SPI发送0xAA,我们的数据线就会变为10101010,通过修改不同的内容,即可修改SPI中0和1的持续时间。比如0xF0即为前半周期为高电平,后半周期为低电平的状态。在SPI的通信模式中,CPHA配置会影响该实验,下图展示了不同采样位置的SPI时序图[1]。CPOL = 0,CPHA = 1:CLK空闲状态 = 低电平,数据在下降沿采样,并在上升沿移出CPOL = 0,CPHA = 0:CLK空闲状态 = 低电平,数据在上升沿采样,并在下降沿移出。_stm32g431cbu6

计算机网络-数据链路层_接收方收到链路层数据后,使用crc检验后,余数为0,说明链路层的传输时可靠传输-程序员宅基地

文章浏览阅读1.2k次,点赞2次,收藏8次。数据链路层习题自测问题1.数据链路(即逻辑链路)与链路(即物理链路)有何区别?“电路接通了”与”数据链路接通了”的区别何在?2.数据链路层中的链路控制包括哪些功能?试讨论数据链路层做成可靠的链路层有哪些优点和缺点。3.网络适配器的作用是什么?网络适配器工作在哪一层?4.数据链路层的三个基本问题(帧定界、透明传输和差错检测)为什么都必须加以解决?5.如果在数据链路层不进行帧定界,会发生什么问题?6.PPP协议的主要特点是什么?为什么PPP不使用帧的编号?PPP适用于什么情况?为什么PPP协议不_接收方收到链路层数据后,使用crc检验后,余数为0,说明链路层的传输时可靠传输

软件测试工程师移民加拿大_无证移民,未受过软件工程师的教育(第1部分)-程序员宅基地

文章浏览阅读587次。软件测试工程师移民加拿大 无证移民,未受过软件工程师的教育(第1部分) (Undocumented Immigrant With No Education to Software Engineer(Part 1))Before I start, I want you to please bear with me on the way I write, I have very little gen...

深度神经网络在训练初期的“梯度消失”或“梯度爆炸”的问题解决:数据标准化(Data Standardization),权重初始化(Weight Initialization),Dropout正则化等_在人工神经网络研究的初始阶段,辛顿针对训练过程中常出现的梯度消失现象, 提供相-程序员宅基地

文章浏览阅读101次。1986年,深度学习(Deep Learning)火爆,它提出了一个名为“深层神经网络”(Deep Neural Networks)的新型机器学习模型。随后几年,神经网络在图像、文本等领域取得了惊艳成果。但是,随着深度学习的应用范围越来越广泛,神经网络在遇到新的任务时出现性能下降或退化的问题。这主要是由于深度神经网络在训练初期面临着“梯度消失”或“梯度爆炸”的问题。_在人工神经网络研究的初始阶段,辛顿针对训练过程中常出现的梯度消失现象, 提供相

随便推点

C++如何做字符串分割(5种方法)_c++ 字符串分割-程序员宅基地

文章浏览阅读10w+次,点赞93次,收藏352次。1、用strtok函数进行字符串分割原型: char *strtok(char *str, const char *delim);功能:分解字符串为一组字符串。参数说明:str为要分解的字符串,delim为分隔符字符串。返回值:从str开头开始的一个个被分割的串。当没有被分割的串时则返回NULL。其它:strtok函数线程不安全,可以使用strtok_r替代。示例://借助strtok实现split#include <string.h>#include <stdio.h&_c++ 字符串分割

2013第四届蓝桥杯 C/C++本科A组 真题答案解析_2013年第四届c a组蓝桥杯省赛真题解答-程序员宅基地

文章浏览阅读2.3k次。1 .高斯日记 大数学家高斯有个好习惯:无论如何都要记日记。他的日记有个与众不同的地方,他从不注明年月日,而是用一个整数代替,比如:4210后来人们知道,那个整数就是日期,它表示那一天是高斯出生后的第几天。这或许也是个好习惯,它时时刻刻提醒着主人:日子又过去一天,还有多少时光可以用于浪费呢?高斯出生于:1777年4月30日。在高斯发现的一个重要定理的日记_2013年第四届c a组蓝桥杯省赛真题解答

基于供需算法优化的核极限学习机(KELM)分类算法-程序员宅基地

文章浏览阅读851次,点赞17次,收藏22次。摘要:本文利用供需算法对核极限学习机(KELM)进行优化,并用于分类。

metasploitable2渗透测试_metasploitable2怎么进入-程序员宅基地

文章浏览阅读1.1k次。一、系统弱密码登录1、在kali上执行命令行telnet 192.168.26.1292、Login和password都输入msfadmin3、登录成功,进入系统4、测试如下:二、MySQL弱密码登录:1、在kali上执行mysql –h 192.168.26.129 –u root2、登录成功,进入MySQL系统3、测试效果:三、PostgreSQL弱密码登录1、在Kali上执行psql -h 192.168.26.129 –U post..._metasploitable2怎么进入

Python学习之路:从入门到精通的指南_python人工智能开发从入门到精通pdf-程序员宅基地

文章浏览阅读257次。本文将为初学者提供Python学习的详细指南,从Python的历史、基础语法和数据类型到面向对象编程、模块和库的使用。通过本文,您将能够掌握Python编程的核心概念,为今后的编程学习和实践打下坚实基础。_python人工智能开发从入门到精通pdf

vscode打开markdown文件 不显示图片 预览markdown文件_vscodemarkdown图片无法显示-程序员宅基地

文章浏览阅读3.2k次,点赞3次,收藏4次。vscode打开markdown文件 不显示图片 预览markdown文件_vscodemarkdown图片无法显示

推荐文章

热门文章

相关标签