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;
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值