JAVA常用操作语句----项目中的总结五

  • 数字的格式化

DecimalFormat df = new DecimalFormat(",###.00");  
double aNumber = 33665448856.6568975; 
String result = df.format(aNumber);  
Sytem. out.println(result);

输出结果为:
33,665,448,856.66 

 

 

  • 分析字符串 

StringTokenizer(String s) 构造一个分析器,使用默认分隔字符(空格,换行,回车,Tab,进纸符) 
StringTokenizer(String s,String delim) delim是自己定义的分隔符 
nextToken() 逐个获取字符串中的语言符号 
boolean hasMoreTokens() 只要字符串还有语言符号将返回true,否则返回false 
countTokens() 得到一共有多少个语言符号

 

 

  • 数组的选择排序

public void ListNum(int[] a){  
  for(int k=0;k<a.length-1;k++){
  int j=k;  
  int mini=a[k];
  for(int i=k+1;i<a.length;i++){  
  if(a[k]>a[i]){
  a[k]=a[i];  
  j=i;
  }  
  }
  a[j]=mini;  
  }  
}

 

 

 

 

  • MD5和一个可逆加密算法相接合的加密和解密程序


import java.security.MessageDigest;
/**
*先通过MD5加密之后,再来一次可逆的加密。
*顺序可以调整,可以选择先用可逆加密,然后再用MD5加密
*/
public class MD5andKL{
//MD5加码。32位
public static String MD5(String inStr) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
return "";
}
char[] charArray = inStr.toCharArray();
byte[] byteArray = new byte[charArray.length];

for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];

byte[] md5Bytes = md5.digest(byteArray);

StringBuffer hexValue = new StringBuffer();

for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}

return hexValue.toString();
}

//可逆的加密算法
public static String KL(String inStr){
//String s = new String(inStr);
char[] a = inStr.toCharArray(); 
  for (int i = 0;i <a.length;i++)  { 
  a[i] = (char)(a[i]^'t'); 
  } 
  String s=new String(a);
  return s; 
}
//加密后解密
public static String JM(String inStr){
char[] a=inStr.toCharArray();
for (int i = 0;i <a.length;i++)  { 
a[i]= (char)(a[i]^'t'); 
  }     
  String k=new String(a);
  return k;
}
//测试主函数
public static void main (String args[]){
String s = new String("admin");
System.out.println("原始:"+s);
System.out.println("MD5后:"+MD5(s));
System.out.println("MD5后再加密:"+KL(MD5(s)));
System.out.println("解密为MD5后的:"+JM(KL(MD5(s))));
}
}

 

 

  • 任意对象转化为JSON
   
   
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 序列化对象为JSON格式 遵循JSON组织公布标准
*
* @date 2008/05/07
*
@version 1.0.0
*/
public class Json {
/** Commons Logging instance. */
private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(Json. class );
/**
*
@param obj 任意对象
*
@return String
*/
public static String object2json(Object obj) {
StringBuilder json
= new StringBuilder();
if (obj == null ) {
json.append(
" /"/" " );
}
else if (obj instanceof String || obj instanceof Integer || obj instanceof Float || obj instanceof Boolean
|| obj instanceof Short || obj instanceof Double || obj instanceof Long || obj instanceof BigDecimal
|| obj instanceof BigInteger || obj instanceof Byte) {
json.append(
" /" " ).append(string2json(obj.toString())).append( " /" " );
}
else if (obj instanceof Object[]) {
json.append(array2json((Object[]) obj));
}
else if (obj instanceof List) {
json.append(list2json((List
<?> ) obj));
}
else if (obj instanceof Map) {
json.append(map2json((Map
<? , ?> ) obj));
}
else if (obj instanceof Set) {
json.append(set2json((Set
<?> ) obj));
}
else {
json.append(bean2json(obj));
}
return json.toString();
}
/**
*
@param bean bean对象
*
@return String
*/
public static String bean2json(Object bean) {
StringBuilder json
= new StringBuilder();
json.append(
" { " );
PropertyDescriptor[] props
= null ;
try {
props
= Introspector.getBeanInfo(bean.getClass(), Object. class ).getPropertyDescriptors();
}
catch (IntrospectionException e) {
}
if (props != null ) {
for ( int i = 0 ; i < props.length; i ++ ) {
try {
String name
= object2json(props[i].getName());
String value
= object2json(props[i].getReadMethod().invoke(bean));
json.append(name);
json.append(
" : " );
json.append(value);
json.append(
" , " );
}
catch (Exception e) {
}
}
json.setCharAt(json.length()
- 1 , ' } ' );
}
else {
json.append(
" } " );
}
return json.toString();
}
/**
*
@param list list对象
*
@return String
*/
public static String list2json(List <?> list) {
StringBuilder json
= new StringBuilder();
json.append(
" [ " );
if (list != null && list.size() > 0 ) {
for (Object obj : list) {
json.append(object2json(obj));
json.append(
" , " );
}
json.setCharAt(json.length()
- 1 , ' ] ' );
}
else {
json.append(
" ] " );
}
return json.toString();
}
/**
*
@param array 对象数组
*
@return String
*/
public static String array2json(Object[] array) {
StringBuilder json
= new StringBuilder();
json.append(
" [ " );
if (array != null && array.length > 0 ) {
for (Object obj : array) {
json.append(object2json(obj));
json.append(
" , " );
}
json.setCharAt(json.length()
- 1 , ' ] ' );
}
else {
json.append(
" ] " );
}
return json.toString();
}
/**
*
@param map map对象
*
@return String
*/
public static String map2json(Map <? , ?> map) {
StringBuilder json
= new StringBuilder();
json.append(
" { " );
if (map != null && map.size() > 0 ) {
for (Object key : map.keySet()) {
json.append(object2json(key));
json.append(
" : " );
json.append(object2json(map.get(key)));
json.append(
" , " );
}
json.setCharAt(json.length()
- 1 , ' } ' );
}
else {
json.append(
" } " );
}
return json.toString();
}
/**
*
@param set 集合对象
*
@return String
*/
public static String set2json(Set <?> set) {
StringBuilder json
= new StringBuilder();
json.append(
" [ " );
if (set != null && set.size() > 0 ) {
for (Object obj : set) {
json.append(object2json(obj));
json.append(
" , " );
}
json.setCharAt(json.length()
- 1 , ' ] ' );
}
else {
json.append(
" ] " );
}
return json.toString();
}
/**
*
@param s 参数
*
@return String
*/
public static String string2json(String s) {
if (s == null )
return "" ;
StringBuilder sb
= new StringBuilder();
for ( int i = 0 ; i < s.length(); i ++ ) {
char ch = s.charAt(i);
switch (ch) {
case ' " ' :
sb.append(
" ///" " );
break ;
case ' // ' :
sb.append(
" " );
break ;
case ' /b ' :
sb.append(
" //b " );
break ;
case ' /f ' :
sb.append(
" //f " );
break ;
case ' /n ' :
sb.append(
" //n " );
break ;
case ' /r ' :
sb.append(
" //r " );
break ;
case ' /t ' :
sb.append(
" //t " );
break ;
case ' / ' :
sb.append(
" /// " );
break ;
default :
if (ch >= ' /u0000 ' && ch <= ' /u001F ' ) {
String ss
= Integer.toHexString(ch);
sb.append(
" //u " );
for ( int k = 0 ; k < 4 - ss.length(); k ++ ) {
sb.append(
' 0 ' );
}
sb.append(ss.toUpperCase());
}
else {
sb.append(ch);
}
}
}
return sb.toString();
}
}

/**

* 用半角的特殊符号代替全角的特殊符号
* 防止特殊字符在传输参数时出现错误
*
*/

public class ReplaceStrE{
public static String rightToError(String ss){
String strs;
String strs1;
String strs2;
String strs3;
String strs4;
try {
strs
= ss.replace( ' ' , ' # ' );
}
catch (Exception ex){
return ss;
}

try {
strs1
= strs.replace( ' ' , ' " ' );
}
catch (Exception ex){
return strs;
}

try {
strs2
= strs1.replace( ' ' , ' & ' );
}
catch (Exception ex){
return strs1;
}

try {
strs3
= strs2.replace( ' ' , ' + ' );
}
catch (Exception ex){
return strs2;
}

try {
strs4
= strs3.replace( ' ' , ' /' ' );
}
catch (Exception ex){
return ss;
}
return strs4;
}
}

/**

* Big5字与Unicode的互换
* 转换后的正常字型
*/

import java.io. * ;

public class MyUtil{
public static String big5ToUnicode(String s){
try {
return new String(s.getBytes( " ISO8859_1 " ), " Big5 " );
}
catch (UnsupportedEncodingException uee){
return s;
}
}

public static String UnicodeTobig5(String s){
try {
return new String(s.getBytes( " Big5 " ), " ISO8859_1 " );
}
catch (UnsupportedEncodingException uee){
return s;
}
}

public static String toHexString(String s){
String str
= "" ;
for ( int i = 0 ; i < s.length(); i ++ ){
int ch = ( int )s.charAt(i);
String s4
= " 0000 " + Integer.toHexString(ch);
str
= str + s4.substring(s4.length() - 4 ) + " " ;
}
return str;
}
}

  • 超强的日期处理类:
    
    
package com.sipgl.eam.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedHashMap;

/**
* 日期公用处理类
*
*
@author SongJun
*
@version 1.3
*/
public class DateUtil {
/**
* 解析一个日期之间的所有月份
*
*
@param beginDateStr
*
@param endDateStr
*
@return
*/
public static ArrayList getMonthList(String beginDateStr, String endDateStr) {
// 指定要解析的时间格式
SimpleDateFormat f = new SimpleDateFormat( " yyyy-MM " );
// 返回的月份列表
String sRet = "" ;

// 定义一些变量
Date beginDate = null ;
Date endDate
= null ;

GregorianCalendar beginGC
= null ;
GregorianCalendar endGC
= null ;
ArrayList list
= new ArrayList();

try {
// 将字符串parse成日期
beginDate = f.parse(beginDateStr);
endDate
= f.parse(endDateStr);

// 设置日历
beginGC = new GregorianCalendar();
beginGC.setTime(beginDate);

endGC
= new GregorianCalendar();
endGC.setTime(endDate);

// 直到两个时间相同
while (beginGC.getTime().compareTo(endGC.getTime()) <= 0 ) {
sRet
= beginGC.get(Calendar.YEAR) + " - "
+ (beginGC.get(Calendar.MONTH) + 1 );
list.add(sRet);
// 以月为单位,增加时间
beginGC.add(Calendar.MONTH, 1 );
}
return list;
}
catch (Exception e) {
e.printStackTrace();
return null ;
}
}

/**
* 解析一个日期段之间的所有日期
*
*
@param beginDateStr
* 开始日期
*
@param endDateStr
* 结束日期
*
@return
*/
public static ArrayList getDayList(String beginDateStr, String endDateStr) {
// 指定要解析的时间格式
SimpleDateFormat f = new SimpleDateFormat( " yyyy-MM-dd " );

// 定义一些变量
Date beginDate = null ;
Date endDate
= null ;

Calendar beginGC
= null ;
Calendar endGC
= null ;
ArrayList list
= new ArrayList();

try {
// 将字符串parse成日期
beginDate = f.parse(beginDateStr);
endDate
= f.parse(endDateStr);

// 设置日历
beginGC = Calendar.getInstance();
beginGC.setTime(beginDate);

endGC
= Calendar.getInstance();
endGC.setTime(endDate);
SimpleDateFormat sdf
= new SimpleDateFormat( " yyyy-MM-dd " );

// 直到两个时间相同
while (beginGC.getTime().compareTo(endGC.getTime()) <= 0 ) {

list.add(sdf.format(beginGC.getTime()));
// 以日为单位,增加时间
beginGC.add(Calendar.DAY_OF_MONTH, 1 );
}
return list;
}
catch (Exception e) {
e.printStackTrace();
return null ;
}
}

public static ArrayList getYearList() {
ArrayList list
= new ArrayList();
Calendar c
= null ;
c
= Calendar.getInstance();
c.setTime(
new Date());
int currYear = Calendar.getInstance().get(Calendar.YEAR);

int startYear = currYear - 5 ;
int endYear = currYear + 10 ;
for ( int i = startYear; i < endYear; i ++ ) {
list.add(
new Integer(i));
}
return list;
}

public static int getCurrYear() {
return Calendar.getInstance().get(Calendar.YEAR);
}

/**
* 得到某一年周的总数
*
*
@param year
*
@return
*/
public static LinkedHashMap getWeekList( int year) {
LinkedHashMap map
= new LinkedHashMap();
Calendar c
= new GregorianCalendar();
c.set(year, Calendar.DECEMBER,
31 , 23 , 59 , 59 );
int count = getWeekOfYear(c.getTime());

SimpleDateFormat sdf
= new SimpleDateFormat( " yyyy-MM-dd " );
String dayOfWeekStart
= "" ;
String dayOfWeekEnd
= "" ;
for ( int i = 1 ; i <= count; i ++ ) {
dayOfWeekStart
= sdf.format(getFirstDayOfWeek(year, i));
dayOfWeekEnd
= sdf.format(getLastDayOfWeek(year, i));
map.put(
new Integer(i), " " + i + " 周(从 " + dayOfWeekStart + " " + dayOfWeekEnd + " ) " );
}
return map;

}

/**
* 得到一年的总周数
*
@param year
*
@return
*/
public static int getWeekCountInYear( int year){
Calendar c
= new GregorianCalendar();
c.set(year, Calendar.DECEMBER,
31 , 23 , 59 , 59 );
int count = getWeekOfYear(c.getTime());
return count;
}

/**
* 取得当前日期是多少周
*
*
@param date
*
@return
*/
public static int getWeekOfYear(Date date) {
Calendar c
= new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setMinimalDaysInFirstWeek(
7 );
c.setTime(date);

return c.get(Calendar.WEEK_OF_YEAR);
}

/**
* 得到某年某周的第一天
*
*
@param year
*
@param week
*
@return
*/
public static Date getFirstDayOfWeek( int year, int week) {
Calendar c
= new GregorianCalendar();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DATE,
1 );

Calendar cal
= (GregorianCalendar) c.clone();
cal.add(Calendar.DATE, week
* 7 );

return getFirstDayOfWeek(cal.getTime());
}

/**
* 得到某年某周的最后一天
*
*
@param year
*
@param week
*
@return
*/
public static Date getLastDayOfWeek( int year, int week) {
Calendar c
= new GregorianCalendar();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DATE,
1 );

Calendar cal
= (GregorianCalendar) c.clone();
cal.add(Calendar.DATE, week
* 7 );

return getLastDayOfWeek(cal.getTime());
}

/**
* 得到某年某月的第一天
*
@param year
*
@param month
*
@return
*/
public static Date getFirestDayOfMonth( int year, int month){
month
= month - 1 ;
Calendar c
= Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);

int day = c.getActualMinimum(c.DAY_OF_MONTH);

c.set(Calendar.DAY_OF_MONTH, day);
return c.getTime();

}

/**
* 提到某年某月的最后一天
*
@param year
*
@param month
*
@return
*/
public static Date getLastDayOfMonth( int year, int month){
month
= month - 1 ;
Calendar c
= Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
int day = c.getActualMaximum(c.DAY_OF_MONTH);
c.set(Calendar.DAY_OF_MONTH, day);
return c.getTime();
}

/**
* 取得当前日期所在周的第一天
*
*
@param date
*
@return
*/
public static Date getFirstDayOfWeek(Date date) {
Calendar c
= new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
// Monday
return c.getTime();
}

/**
* 取得当前日期所在周的最后一天
*
*
@param date
*
@return
*/
public static Date getLastDayOfWeek(Date date) {
Calendar c
= new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()
+ 6 ); // Sunday
return c.getTime();
}

}

  • 一个超强的字符串处理类
   
   
package net.java2000.tools;

/**
* Title: Java Bean 工具
* Description:
* Copyright: Copyright (c) 2001
* Company: JAVA世纪网
http://www.java2000.net
*
@author 赵学庆
*
@version 1.0
*/
import java.util. * ;
import java.util.regex.Pattern;

public class StrTools {
/**
* 分割字符串
*
*
@param str String 原始字符串
*
@param splitsign String 分隔符
*
@return String[] 分割后的字符串数组
*/
@SuppressWarnings(
" unchecked " )
public static String[] split(String str, String splitsign) {
int index;
if (str == null || splitsign == null )
return null ;
ArrayList al
= new ArrayList();
while ((index = str.indexOf(splitsign)) != - 1 ) {
al.add(str.substring(
0 , index));
str
= str.substring(index + splitsign.length());
}
al.add(str);
return (String[]) al.toArray( new String[ 0 ]);
}

/**
* 替换字符串
*
*
@param from String 原始字符串
*
@param to String 目标字符串
*
@param source String 母字符串
*
@return String 替换后的字符串
*/
public static String replace(String from, String to, String source) {
if (source == null || from == null || to == null )
return null ;
StringBuffer bf
= new StringBuffer( "" );
int index = - 1 ;
while ((index = source.indexOf(from)) != - 1 ) {
bf.append(source.substring(
0 , index) + to);
source
= source.substring(index + from.length());
index
= source.indexOf(from);
}
bf.append(source);
return bf.toString();
}

/**
* 替换字符串,能能够在HTML页面上直接显示(替换双引号和小于号)
*
*
@param str String 原始字符串
*
@return String 替换后的字符串
*/
public static String htmlencode(String str) {
if (str == null ) {
return null ;
}

return replace( " /" " , " &quot; " , replace( " < " , " &lt; " , str));
}

/**
* 替换字符串,将被编码的转换成原始码(替换成双引号和小于号)
*
*
@param str String
*
@return String
*/
public static String htmldecode(String str) {
if (str == null ) {
return null ;
}

return replace( " &quot; " , " /" " , replace( " &lt; " , " < " , str));
}

private static final String _BR = " <br/> " ;

/**
* 在页面上直接显示文本内容,替换小于号,空格,回车,TAB
*
*
@param str String 原始字符串
*
@return String 替换后的字符串
*/
public static String htmlshow(String str) {
if (str == null ) {
return null ;
}

str
= replace( " < " , " &lt; " , str);
str
= replace( " " , " &nbsp; " , str);
str
= replace( " /r/n " , _BR, str);
str
= replace( " /n " , _BR, str);
str
= replace( " /t " , " &nbsp;&nbsp;&nbsp;&nbsp; " , str);
return str;
}

/**
* 返回指定字节长度的字符串
*
*
@param str String 字符串
*
@param length int 指定长度
*
@return String 返回的字符串
*/
public static String toLength(String str, int length) {
if (str == null ) {
return null ;
}
if (length <= 0 ) {
return "" ;
}
try {
if (str.getBytes( " GBK " ).length <= length) {
return str;
}
}
catch (Exception ex) {
}
StringBuffer buff
= new StringBuffer();

int index = 0 ;
char c;
length
-= 3 ;
while (length > 0 ) {
c
= str.charAt(index);
if (c < 128 ) {
length
-- ;
}
else {
length
-- ;
length
-- ;
}
buff.append(c);
index
++ ;
}
buff.append(
" ... " );
return buff.toString();
}

/**
* 判断是否为整数
*
*
@param str 传入的字符串
*
@return 是整数返回true,否则返回false
*/
public static boolean isInteger(String str) {
Pattern pattern
= Pattern.compile( " ^[-//+]?[//d]*$ " );
return pattern.matcher(str).matches();
}

/**
* 判断是否为浮点数,包括double和float
*
*
@param str 传入的字符串
*
@return 是浮点数返回true,否则返回false
*/
public static boolean isDouble(String str) {
Pattern pattern
= Pattern.compile( " ^[-//+]?[.//d]*$ " );
return pattern.matcher(str).matches();
}

/**
* 判断输入的字符串是否符合Email样式.
*
*
@param str 传入的字符串
*
@return 是Email样式返回true,否则返回false
*/
public static boolean isEmail(String str) {
Pattern pattern
= Pattern.compile( " ^//w+([-+.]//w+)*@//w+([-.]//w+)*//.//w+([-.]//w+)*$ " );
return pattern.matcher(str).matches();
}

/**
* 判断输入的字符串是否为纯汉字
*
*
@param str 传入的字符窜
*
@return 如果是纯汉字返回true,否则返回false
*/
public static boolean isChinese(String str) {
Pattern pattern
= Pattern.compile( " [/u0391-/uFFE5]+$ " );
return pattern.matcher(str).matches();
}

/**
* 是否为空白,包括null和""
*
*
@param str
*
@return
*/
public static boolean isBlank(String str) {
return str == null || str.trim().length() == 0 ;
}

/**
* 判断是否为质数
*
*
@param x
*
@return
*/
public static boolean isPrime( int x) {
if (x <= 7 ) {
if (x == 2 || x == 3 || x == 5 || x == 7 )
return true ;
}
int c = 7 ;
if (x % 2 == 0 )
return false ;
if (x % 3 == 0 )
return false ;
if (x % 5 == 0 )
return false ;
int end = ( int ) Math.sqrt(x);
while (c <= end) {
if (x % c == 0 ) {
return false ;
}
c
+= 4 ;
if (x % c == 0 ) {
return false ;
}
c
+= 2 ;
if (x % c == 0 ) {
return false ;
}
c
+= 4 ;
if (x % c == 0 ) {
return false ;
}
c
+= 2 ;
if (x % c == 0 ) {
return false ;
}
c
+= 4 ;
if (x % c == 0 ) {
return false ;
}
c
+= 6 ;
if (x % c == 0 ) {
return false ;
}
c
+= 2 ;
if (x % c == 0 ) {
return false ;
}
c
+= 6 ;
}
return true ;
}

public static void main(String[] args) {
String[] numbers
= { " 12345 " , " -12345 " , " 123.45 " , " -123.45 " , " .12345 " , " -.12345 " , " a12345 " , " 12345a " , " 123.a45 " };
for (String str : numbers) {
System.out.println(str
+ " = " + isInteger(str) + " " + isDouble(str));
}

String[] emails
= { " 1@2.com " , " 1.2@3.com " , " 1@3.4.5.com " };
for (String str : emails) {
System.out.println(str
+ " = " + isEmail(str));
}
String[] chineses
= { " 中国 " , " 1中国 " , " 中国1 " , " 1中国2 " , " 中1国 " };
for (String str : chineses) {
System.out.println(str
+ " = " + isChinese(str));
}
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值