import java.util.Arrays; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern;public class CommonBaseCode { /** * 判断任意一个整数是否素数 * * @param n * @return boolean */ public static boolean isPrimes(int n) { for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) { return false; } } return true; } /** * 获得任意一个整数的阶乘,递归 * * @param n * @return n! */ public static int factorial(int n) { if (n == 1) { return 1; } return n * factorial(n - 1); } /** * 将指定byte数组以16进制的形式打印到控制台 * * @param hint * String * @param b * byte[] * @return void */ public static void printHexString(String hint, byte[] b) { System.out.print(hint); for (int i = 0; i < b.length; i++) { String hex = Integer.toHexString(b[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } System.out.print(hex.toUpperCase() + " "); } System.out.println(""); } /** * 人民币转成大写 * * @param value * @return String */ public static String hangeToBig(double value) { char[] hunit = { '拾', '佰', '仟' }; // 段内位置表示 char[] vunit = { '万', '亿' }; // 段名表示 char[] digit = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' }; // 数字表示 long midVal = (long) (value * 100); // 转化成整形 String valStr = String.valueOf(midVal); // 转化成字符串 String head = valStr.substring(0, valStr.length() - 2); // 取整数部分 String rail = valStr.substring(valStr.length() - 2); // 取小数部分 String prefix = ""; // 整数部分转化的结果 String suffix = ""; // 小数部分转化的结果 // 处理小数点后面的数 if (rail.equals("00")) { // 如果小数部分为0 suffix = "整"; } else { suffix = digit[rail.charAt(0) - '0'] + "角" + digit[rail.charAt(1) - '0'] + "分"; // 否则把角分转化出来 } // 处理小数点前面的数 char[] chDig = head.toCharArray(); // 把整数部分转化成字符数组 char zero = '0'; // 标志'0'表示出现过0 byte zeroSerNum = 0; // 连续出现0的次数 for (int i = 0; i < chDig.length; i++) { // 循环处理每个数字 int idx = (chDig.length - i - 1) % 4; // 取段内位置 int vidx = (chDig.length - i - 1) / 4; // 取段位置 if (chDig[i] == '0') { // 如果当前字符是0 zeroSerNum++; // 连续0次数递增 if (zero == '0') { // 标志 zero = digit[0]; } else if (idx == 0 && vidx > 0 && zeroSerNum < 4) { prefix += vunit[vidx - 1]; zero = '0'; } continue; } zeroSerNum = 0; // 连续0次数清零 if (zero != '0') { // 如果标志不为0,则加上,例如万,亿什么的 prefix += zero; zero = '0'; } prefix += digit[chDig[i] - '0']; // 转化该数字表示 if (idx > 0) prefix += hunit[idx - 1]; if (idx == 0 && vidx > 0) { prefix += vunit[vidx - 1]; // 段结束位置应该加上段名如万,亿 } } if (prefix.length() > 0) prefix += '圆'; // 如果整数部分存在,则有圆的字样 return prefix + suffix; // 返回正确表示 } /** * 全角字符转半角字符 * * @param QJStr * @return String */ public static final String QJToBJChange(String QJStr) { char[] chr = QJStr.toCharArray(); String str = ""; for (int i = 0; i < chr.length; i++) { chr[i] = (char) ((int) chr[i] - 65248); str += chr[i]; } return str; } /** * 去掉字符串中重复的子字符串 * * @param str * @return String */ @SuppressWarnings("unused") private static String removeSameString(String str) { Set<String> mLinkedSet = new LinkedHashSet<String>(); String[] strArray = str.split(" "); StringBuffer sb = new StringBuffer(); for (int i = 0; i < strArray.length; i++) { if (!mLinkedSet.contains(strArray[i])) { mLinkedSet.add(strArray[i]); sb.append(strArray[i] + " "); } } System.out.println(mLinkedSet); return sb.toString().substring(0, sb.toString().length() - 1); } /** * 判断是不是合法手机 handset 手机号码 */ public static boolean isHandset(String handset) { try { if (!handset.substring(0, 1).equals("1")) { return false; } if (handset == null || handset.length() != 11) { return false; } String check = "^[0123456789]+$"; Pattern regex = Pattern.compile(check); Matcher matcher = regex.matcher(handset); boolean isMatched = matcher.matches(); if (isMatched) { return true; } else { return false; } } catch (RuntimeException e) { return false; } } /** * 从指定的字符串中提取Email content 指定的字符串 */ public static String parse(String content) { String email = null; if (content == null || content.length() < 1) { return email; } // 找出含有@ int beginPos; int i; String token = "@"; String preHalf = ""; String sufHalf = ""; beginPos = content.indexOf(token); if (beginPos > -1) { // 前项扫描 String s = null; i = beginPos; while (i > 0) { s = content.substring(i - 1, i); if (isLetter(s)) preHalf = s + preHalf; else break; i--; } // 后项扫描 i = beginPos + 1; while (i < content.length()) { s = content.substring(i, i + 1); if (isLetter(s)) sufHalf = sufHalf + s; else break; i++; } // 判断合法性 email = preHalf + "@" + sufHalf; if (isEmail(email)) { return email; } } return null; } /** * 判断是不是合法Email email Email地址 */ public static boolean isEmail(String email) { try { if (email == null || email.length() < 1 || email.length() > 256) { return false; } String check = "^([0-9a-zA-Z]+[_.0-9a-zA-Z-]+)@([a-zA-Z0-9-]+[.])+([a-zA-Z]{2,3})$"; Pattern regex = Pattern.compile(check); Matcher matcher = regex.matcher(email); boolean isMatched = matcher.matches(); if (isMatched) { return true; } else { return false; } } catch (RuntimeException e) { return false; } } /** * 判断是不是合法字符 c 要判断的字符 */ public static boolean isLetter(String c) { boolean result = false; if (c == null || c.length() < 0) { return false; } // a-z if (c.compareToIgnoreCase("a") >= 0 && c.compareToIgnoreCase("z") <= 0) { return true; } // 0-9 if (c.compareToIgnoreCase("0") >= 0 && c.compareToIgnoreCase("9") <= 0) { return true; } // . - _ if (c.equals(".") || c.equals("-") || c.equals("_")) { return true; } return result; } /** * 对给定的字符数组进行字典排序 * * @param chs * 目标字符数组 * @param upperFisrt * 大写字母是否在前 * @return 排序后的字符数组 */ public static char[] sortChars(char[] chs, final boolean upperFisrt) { Character[] srcArray = new Character[chs.length]; char[] retArray = new char[chs.length]; int index = 0; for (char ch : chs) { srcArray[index++] = ch; } Arrays.sort(srcArray, new Comparator<Character>() { public int compare(Character c1, Character c2) { char ch1 = Character.toUpperCase(c1); char ch2 = Character.toUpperCase(c2); if (ch1 == ch2) { int tempRet = c1.charValue() - c2.charValue(); return upperFisrt ? tempRet : -tempRet; } else { return ch1 - ch2; } } }); index = 0; for (char ch : srcArray) { retArray[index++] = ch; } return retArray; } public static void main(String[] args) { System.out.print(hangeToBig(166666665555.34)); }}
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("\"", """, replace("<", "<", str)); } /** * 替换字符串,将被编码的转换成原始码(替换成双引号和小于号) * * @param str * String * @return String */ public static String htmldecode(String str) { if (str == null) { return null; } return replace(""", "\"", replace("<", "<", 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("<", "<", str); str = replace(" ", " ", str); str = replace("\r\n", _BR, str); str = replace("\n", _BR, str); str = replace("\t", " ", 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 = { "[email protected]", "[email protected]", "[email protected]" }; 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)); } } }
class Parent { // 静态变量 public static String p_StaticField = "父类--静态变量"; // 变量 public String p_Field = "父类--变量"; // 静态初始化块 static { System.out.println(p_StaticField); System.out.println("父类--静态初始化块"); } // 初始化块 { System.out.println(p_Field); System.out.println("父类--初始化块"); } // 构造器 public Parent() { System.out.println("父类--构造器"); } }public class SubClass extends Parent { // 静态变量 public static String s_StaticField = "子类--静态变量"; // 变量 public String s_Field = "子类--变量"; // 静态初始化块 static { System.out.println(s_StaticField); System.out.println("子类--静态初始化块"); } // 初始化块 { System.out.println(s_Field); System.out.println("子类--初始化块"); } // 构造器 public SubClass() { System.out.println("子类--构造器"); } // 程序入口 public static void main(String[] args) { new SubClass(); } }
我也来贡献一个 邮件转编码的: /* * Base64.java * * Created on 2008-5-5, 11:11:32 * * To change this template, choose Tools | Templates * and open the template in the editor. */package com.mop.pushmail.utils;import javax.mail.internet.MimeUtility; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.InputStreamReader; //import java.io.RandomAccessFile; /** * * @author muning */ public class Base64 { public Base64() { }
public static BufferedReader decode(String b64string) throws Exception { return new BufferedReader( new InputStreamReader( MimeUtility.decode( new ByteArrayInputStream(b64string.getBytes()), "base64"))); }
public void getPropertiesFromClasspath(String file){ ResourceBundle rb = ResourceBundle.getBundle(file); Enumeration en = rb.getKeys(); while(en.hasMoreElements()){ String key = String.valueOf(en.nextElement()); cachedFile.put(key,rb.getString(key)); } }
public String getValueByKey(String key){ if (cachedFile!=null && cachedFile.size()!=0 && key !=null) { return String.valueOf(cachedFile.get(key)); } return "no data found"; }
public int getDataCount(){ if (cachedFile!=null) { return cachedFile.size(); }else{ return 0; } }
public List getKeys(){ List result = new ArrayList(); Enumeration en = cachedFile.keys(); if (cachedFile!=null) { while (en.hasMoreElements()) { result.add(en.nextElement()); } } return result; }
//constructor sets window's title bar string and dimension public ShowColors() { super("Using colors");
setSize(400,130); setVisible(true);
} //draw rectangles and Strings in different colors public void paint(Graphics g) { //call superclass's paint method super.paint(g);
//set new drawing colors using integers g.setColor(new Color(255,0,0)); g.fillRect(25,25,100,20); g.drawString("Current RGB:"+g.getColor(),130,40);
//set new drawing color using floats g.setColor(new Color(0.0f,1.0f,0.0f)); g.fillRect(25,50,100,20); g.drawString("Current RGB:"+g.getColor(),130,65);
//set new drawing color using static color objects g.setColor(Color.blue); g.fillRect(25,75,100,20); g.drawString("Current RGB:"+g.getColor(),130,90);
//display individual RGB values Color color = Color.magenta; g.setColor(color); g.fillRect(25,100,100,20); g.drawString("RBG values:"+color.getRed()+","+color.getGreen()+","+color.getBlue(),130,115);
楼主【jdlsfl】截止到2008-07-28 19:56:34的历史汇总数据(不包括此帖):
发帖的总数量:77 发帖的总分数:3095 每贴平均分数:40
回帖的总数量:2939 得分贴总数量:1594 回帖的得分率:54%
结贴的总数量:76 结贴的总分数:2795
无满意结贴数:0 无满意结贴分:0
未结的帖子数:1 未结的总分数:300
结贴的百分比:98.70 % 结分的百分比:90.31 %
无满意结贴率:0.00 % 无满意结分率:0.00 %
值得尊敬
getMilliseconds().得到毫秒数。还有一个
Map里面想得到Key和value可以用EntrySet()映射,然后getValue,getKey。。
import java.util.Calendar;
import java.util.Date;
/**
* 功能:计算时间
* 上月开始、上月结束、本月开始、本月结束、上周开始、上周结束、本周开始、本周结束、昨天开始、昨天结束、今天开始、今天结束
* @see
* @version 2007-06-07
*
*/public class StartAndEndOfDate {
public static enum DateTag {LAST_MONTH_START,LAST_MONTH_END,THIS_MONTH_START,THIS_MONTH_END,LAST_WEEK_START,LAST_WEEK_END,
THIS_WEEK_START,THIS_WEEK_END,YESTERDAY_START,YESTERDAY_END,TODAY_START,TODAY_END,NOW};
/**
* 功能:计算时间
* 上月开始、上月结束、本月开始、本月结束、上周开始、上周结束、本周开始、本周结束、昨天开始、昨天结束、今天开始、今天结束
* 格式:2007-06-01 00:00:00 2007-06-30 23:59:59
* 本月结束、本周结束、今天结束 都指的是当前日期时间
* 一周按照:星期一至星期天来计算
* @param tag
* @return String
*/
public static String getStartAndEndDate(DateTag tag){
String resultString;
Calendar cal = Calendar.getInstance();
Date date = new Date();
java.text.DateFormat formatFull = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String now = formatFull.format(date);
java.text.DateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
switch (tag){
case LAST_MONTH_START://上月开始
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DATE, 1);
String lastMonthStart = format.format(cal.getTime())+" 00:00:00";//上月开始(上月1号)
cal.clear();
resultString = lastMonthStart;
break;
case LAST_MONTH_END://上月结束
cal=Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DATE,cal.getActualMaximum(Calendar.DAY_OF_MONTH));
String lastMonthEnd = format.format(cal.getTime())+" 23:59:59";//上月结束(上月最后一天)
cal.clear();
resultString = lastMonthEnd;
break;
case THIS_MONTH_START://本月开始
cal=Calendar.getInstance();
cal.add(Calendar.MONDAY,0);
cal.set(Calendar.DAY_OF_MONTH, 1);
String thisMonthStart = format.format(cal.getTime())+" 00:00:00";//本月开始(本月1号)
cal.clear();
resultString = thisMonthStart;
break;
case THIS_MONTH_END://本月结束
String thisMonthEnd = now;//本月结束(即:当前时间)
resultString = thisMonthEnd;
break;
case LAST_WEEK_START://上周开始
cal=Calendar.getInstance();
cal.add(Calendar.WEEK_OF_YEAR, -1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
String lastWeekStart = format.format(cal.getTime())+" 00:00:00";//上周开始(即:上周一)
cal.clear();
resultString = lastWeekStart;
break;
case LAST_WEEK_END://上周结束
cal=Calendar.getInstance();
cal.add(Calendar.WEEK_OF_YEAR, 0);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String lastWeekEnd = format.format(cal.getTime())+" 23:59:59";//上周结束(即:上周日)
cal.clear();
resultString = lastWeekEnd;
break;
case THIS_WEEK_START://本周开始
cal=Calendar.getInstance();
cal.add(Calendar.WEEK_OF_YEAR, 0);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
String thisWeekStart = format.format(cal.getTime())+" 00:00:00";//本周开始(即:本周一)
cal.clear();
resultString = thisWeekStart;
break;
case THIS_WEEK_END://本周结束
String thisWeekEnd = now;//本周结束(即:当前时间)
resultString = thisWeekEnd;
break;
case YESTERDAY_START://昨天开始
cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -1);
format = new java.text.SimpleDateFormat("yyyy-MM-dd");
String yesterdayStart= format.format(cal.getTime());
yesterdayStart = yesterdayStart+" 00:00:00";//昨天开始
cal.clear();
resultString = yesterdayStart;
break;
case YESTERDAY_END://昨天结束
cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -1);
format = new java.text.SimpleDateFormat("yyyy-MM-dd");
String yesterdayEnd= format.format(cal.getTime());
yesterdayEnd = yesterdayEnd+" 23:59:59";//昨天结束
cal.clear();
resultString = yesterdayEnd;
break;
case TODAY_START://今天开始
String todayStart=format.format(date)+" 00:00:00";//今天开始
resultString = todayStart;
break;
case TODAY_END://今天结束
String todayEnd = now;//今天结束(即;当前时间)
resultString = todayEnd;
break;
default://没有匹配的,返回当前时间
resultString = now;
}
return resultString; }}
String rate="0.00%";
if(count!=0){
rate=(double)success/count+"";
if(success/count>=1){
rate=rate.replace(".","");
if(rate.length()<6){
while(rate.length()<=6){
rate=rate+"0";
}
rate=rate.substring(0,3)+"."+rate.substring(3, 5)+"%";
}else {
if(Integer.parseInt(rate.charAt(5)+"")>=5){
rate=rate.substring(0,3)+"."+rate.substring(3, 4)
+(Integer.parseInt(rate.charAt(5)+"")+1)+"%";
}else{
rate=rate.substring(0,3)+"."+rate.substring(3, 5)+"%";
}
}
}else{
if(rate.length()<6){
while(rate.length()<=6){
rate=rate+"0";
}
rate=rate.substring(2,4)+"."+rate.substring(4, 6)+"%";
}else {
if(Integer.parseInt(rate.charAt(5)+"")>=5){
rate=rate.substring(2,4)+"."+rate.substring(4, 5)
+(Integer.parseInt(rate.charAt(5)+"")+1)+"%";
}else{
rate=rate.substring(2,4)+"."+rate.substring(4, 6)+"%";
}
}
}
}
return rate;
}
/**
* 设置request参数给定义的bean
*
* @param bean 接受参数的对象
* @param request HttpServletRequest请求
* @return 赋值后的对象
*/
public static Object setParaToUsr(Object bean, HttpServletRequest request) {
if (request == null) {
System.out.println("invalid request...");
return bean;
}
try {
Class objClass = bean.getClass();
Field[] fields = objClass.getDeclaredFields(); for (int i = 0; i < fields.length; i++) {
String attribute = fields[i].getName();
if (attribute.equals("ip")) {
PropertyUtils.setProperty(bean, attribute, request
.getRemoteAddr());
continue;
} String value = request.getParameter(attribute);
if (value != null && value.length() != 0) {
System.out.println("attribute " + attribute
+ "'s value is:" + value);
PropertyUtils.setProperty(bean, attribute, value);
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return bean;
}
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class CommonBaseCode {
/**
* 判断任意一个整数是否素数
*
* @param n
* @return boolean
*/
public static boolean isPrimes(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
} /**
* 获得任意一个整数的阶乘,递归
*
* @param n
* @return n!
*/
public static int factorial(int n) {
if (n == 1) {
return 1;
}
return n * factorial(n - 1);
} /**
* 将指定byte数组以16进制的形式打印到控制台
*
* @param hint
* String
* @param b
* byte[]
* @return void
*/
public static void printHexString(String hint, byte[] b) {
System.out.print(hint);
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
System.out.print(hex.toUpperCase() + " ");
}
System.out.println("");
} /**
* 人民币转成大写
*
* @param value
* @return String
*/
public static String hangeToBig(double value) {
char[] hunit = { '拾', '佰', '仟' }; // 段内位置表示
char[] vunit = { '万', '亿' }; // 段名表示
char[] digit = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' }; // 数字表示
long midVal = (long) (value * 100); // 转化成整形
String valStr = String.valueOf(midVal); // 转化成字符串 String head = valStr.substring(0, valStr.length() - 2); // 取整数部分
String rail = valStr.substring(valStr.length() - 2); // 取小数部分 String prefix = ""; // 整数部分转化的结果
String suffix = ""; // 小数部分转化的结果
// 处理小数点后面的数
if (rail.equals("00")) { // 如果小数部分为0
suffix = "整";
} else {
suffix = digit[rail.charAt(0) - '0'] + "角"
+ digit[rail.charAt(1) - '0'] + "分"; // 否则把角分转化出来
}
// 处理小数点前面的数
char[] chDig = head.toCharArray(); // 把整数部分转化成字符数组
char zero = '0'; // 标志'0'表示出现过0
byte zeroSerNum = 0; // 连续出现0的次数
for (int i = 0; i < chDig.length; i++) { // 循环处理每个数字
int idx = (chDig.length - i - 1) % 4; // 取段内位置
int vidx = (chDig.length - i - 1) / 4; // 取段位置
if (chDig[i] == '0') { // 如果当前字符是0
zeroSerNum++; // 连续0次数递增
if (zero == '0') { // 标志
zero = digit[0];
} else if (idx == 0 && vidx > 0 && zeroSerNum < 4) {
prefix += vunit[vidx - 1];
zero = '0';
}
continue;
}
zeroSerNum = 0; // 连续0次数清零
if (zero != '0') { // 如果标志不为0,则加上,例如万,亿什么的
prefix += zero;
zero = '0';
}
prefix += digit[chDig[i] - '0']; // 转化该数字表示
if (idx > 0)
prefix += hunit[idx - 1];
if (idx == 0 && vidx > 0) {
prefix += vunit[vidx - 1]; // 段结束位置应该加上段名如万,亿
}
} if (prefix.length() > 0)
prefix += '圆'; // 如果整数部分存在,则有圆的字样
return prefix + suffix; // 返回正确表示
} /**
* 全角字符转半角字符
*
* @param QJStr
* @return String
*/
public static final String QJToBJChange(String QJStr) {
char[] chr = QJStr.toCharArray();
String str = "";
for (int i = 0; i < chr.length; i++) {
chr[i] = (char) ((int) chr[i] - 65248);
str += chr[i];
}
return str;
} /**
* 去掉字符串中重复的子字符串
*
* @param str
* @return String
*/
@SuppressWarnings("unused")
private static String removeSameString(String str) {
Set<String> mLinkedSet = new LinkedHashSet<String>();
String[] strArray = str.split(" ");
StringBuffer sb = new StringBuffer(); for (int i = 0; i < strArray.length; i++) {
if (!mLinkedSet.contains(strArray[i])) {
mLinkedSet.add(strArray[i]);
sb.append(strArray[i] + " ");
}
}
System.out.println(mLinkedSet);
return sb.toString().substring(0, sb.toString().length() - 1);
} /**
* 判断是不是合法手机 handset 手机号码
*/
public static boolean isHandset(String handset) {
try {
if (!handset.substring(0, 1).equals("1")) {
return false;
}
if (handset == null || handset.length() != 11) {
return false;
}
String check = "^[0123456789]+$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(handset);
boolean isMatched = matcher.matches();
if (isMatched) {
return true;
} else {
return false;
}
} catch (RuntimeException e) {
return false;
}
} /**
* 从指定的字符串中提取Email content 指定的字符串
*/
public static String parse(String content) {
String email = null;
if (content == null || content.length() < 1) {
return email;
}
// 找出含有@
int beginPos;
int i;
String token = "@";
String preHalf = "";
String sufHalf = ""; beginPos = content.indexOf(token);
if (beginPos > -1) {
// 前项扫描
String s = null;
i = beginPos;
while (i > 0) {
s = content.substring(i - 1, i);
if (isLetter(s))
preHalf = s + preHalf;
else
break;
i--;
}
// 后项扫描
i = beginPos + 1;
while (i < content.length()) {
s = content.substring(i, i + 1);
if (isLetter(s))
sufHalf = sufHalf + s;
else
break;
i++;
}
// 判断合法性
email = preHalf + "@" + sufHalf;
if (isEmail(email)) {
return email;
}
}
return null;
} /**
* 判断是不是合法Email email Email地址
*/
public static boolean isEmail(String email) {
try {
if (email == null || email.length() < 1 || email.length() > 256) {
return false;
} String check = "^([0-9a-zA-Z]+[_.0-9a-zA-Z-]+)@([a-zA-Z0-9-]+[.])+([a-zA-Z]{2,3})$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(email);
boolean isMatched = matcher.matches();
if (isMatched) {
return true;
} else {
return false;
}
} catch (RuntimeException e) {
return false;
}
} /**
* 判断是不是合法字符 c 要判断的字符
*/
public static boolean isLetter(String c) {
boolean result = false; if (c == null || c.length() < 0) {
return false;
}
// a-z
if (c.compareToIgnoreCase("a") >= 0 && c.compareToIgnoreCase("z") <= 0) {
return true;
}
// 0-9
if (c.compareToIgnoreCase("0") >= 0 && c.compareToIgnoreCase("9") <= 0) {
return true;
}
// . - _
if (c.equals(".") || c.equals("-") || c.equals("_")) {
return true;
}
return result;
} /**
* 对给定的字符数组进行字典排序
*
* @param chs
* 目标字符数组
* @param upperFisrt
* 大写字母是否在前
* @return 排序后的字符数组
*/
public static char[] sortChars(char[] chs, final boolean upperFisrt) {
Character[] srcArray = new Character[chs.length];
char[] retArray = new char[chs.length];
int index = 0; for (char ch : chs) {
srcArray[index++] = ch;
} Arrays.sort(srcArray, new Comparator<Character>() {
public int compare(Character c1, Character c2) {
char ch1 = Character.toUpperCase(c1);
char ch2 = Character.toUpperCase(c2); if (ch1 == ch2) {
int tempRet = c1.charValue() - c2.charValue();
return upperFisrt ? tempRet : -tempRet;
} else {
return ch1 - ch2;
}
}
}); index = 0; for (char ch : srcArray) {
retArray[index++] = ch;
} return retArray;
} public static void main(String[] args) {
System.out.print(hangeToBig(166666665555.34));
}}
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("\"", """, replace("<", "<", str));
} /**
* 替换字符串,将被编码的转换成原始码(替换成双引号和小于号)
*
* @param str
* String
* @return String
*/
public static String htmldecode(String str) {
if (str == null) {
return null;
} return replace(""", "\"", replace("<", "<", 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("<", "<", str);
str = replace(" ", " ", str);
str = replace("\r\n", _BR, str);
str = replace("\n", _BR, str);
str = replace("\t", " ", 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 = { "[email protected]", "[email protected]", "[email protected]" };
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));
}
}
}
class Parent {
// 静态变量
public static String p_StaticField = "父类--静态变量";
// 变量
public String p_Field = "父类--变量"; // 静态初始化块
static {
System.out.println(p_StaticField);
System.out.println("父类--静态初始化块");
} // 初始化块
{
System.out.println(p_Field);
System.out.println("父类--初始化块");
} // 构造器
public Parent() {
System.out.println("父类--构造器");
}
}public class SubClass extends Parent {
// 静态变量
public static String s_StaticField = "子类--静态变量";
// 变量
public String s_Field = "子类--变量";
// 静态初始化块
static {
System.out.println(s_StaticField);
System.out.println("子类--静态初始化块");
}
// 初始化块
{
System.out.println(s_Field);
System.out.println("子类--初始化块");
} // 构造器
public SubClass() {
System.out.println("子类--构造器");
} // 程序入口
public static void main(String[] args) {
new SubClass();
}
}
邮件转编码的:
/*
* Base64.java
*
* Created on 2008-5-5, 11:11:32
*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/package com.mop.pushmail.utils;import javax.mail.internet.MimeUtility;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
//import java.io.RandomAccessFile;
/**
*
* @author muning
*/
public class Base64 { public Base64() {
}
public static BufferedReader decode(String b64string) throws Exception {
return new BufferedReader(
new InputStreamReader(
MimeUtility.decode(
new ByteArrayInputStream(b64string.getBytes()), "base64")));
}
public static void main(String args[]) throws Exception{
// if (args.length != 2){
// System.err.println("Usage: java Base64 encORdec yourStrings");
// System.exit(0);
// }
// String str1 = args[0].trim();
// String str1 = "dec";
// String str2 = "好人";
// String str3 = "";
// if (str1.equalsIgnoreCase("enc")){
// System.out.println(encodeAsString(str2));
// }
// else if(str1.equalsIgnoreCase("dec")){
// System.out.println(decodeAsString(str3));
// }
// else{
// System.err.println("Usage: java Base64 encORdec yourStrings");
// System.exit(0);
// }
// String filename = "D:\\111.pdf";
// Base64Encode(filename);
// String filename1 = "D:\\111.txt";
// Base64Decode(filename1);
// System.out.println(System.getProperties());
String test = "穆宁";
byte[] bytes = test.getBytes("UTF-8");
String result = new String(bytes, "UTF-8");
System.out.println("Receive value: [" + result + "].");
}
public static String Base64Encode(String filename) {
//int ret = -1;
String content = null;
FileInputStream fileforinput = null;
try {
fileforinput = new FileInputStream(filename);
byte[] bytes = new byte[fileforinput.available()];
fileforinput.read(bytes);
content = new sun.misc.BASE64Encoder().encode(bytes);
fileforinput.close();
return content;
// RandomAccessFile inOut = new RandomAccessFile("d:\\doc64.txt","rw");
// inOut.write(content.getBytes());
// inOut.close();
// ret = 0;
}
catch (Exception ex) {
ex.printStackTrace();
return null;
}
// return ret;
}
// 文件内容是base64编码的,还原成base64编码前的模样
public static byte[] Base64Decode(String filename) {
String original = null;
FileInputStream fis = null;
byte[] bytes = null;
byte[] result = null;
try {
fis = new FileInputStream(filename);
bytes = new byte[fis.available()];
fis.read(bytes);
original = new String(bytes);
// String temp = new String(bytes,"utf-8");
// original = new String(temp.getBytes("iso-8859-1"),"utf-8");
result = new sun.misc.BASE64Decoder().decodeBuffer(original.trim());
}
catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
public static String decodeAsString(String b64string) throws Exception {
if (b64string == null) {
return b64string;
}
String returnString = decode(b64string).readLine();
if (returnString == null) {
return returnString;
}
return returnString.trim();
}
public static ByteArrayOutputStream encode(String plaintext,String charset) throws Exception{
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] in = plaintext.getBytes(charset);
ByteArrayOutputStream inStream = new ByteArrayOutputStream();
inStream.write(in, 0, in.length);
// pad
if ((in.length % 3 ) == 1){
inStream.write(0);
inStream.write(0);
}
else if((in.length % 3 ) == 2){
inStream.write(0);
}
inStream.writeTo( MimeUtility.encode(out, "base64") );
return out;
}
public static String encodeAsString(String plaintext) throws Exception {
return encode(plaintext,"UTF-8").toString();
}
public static String encodeAsString(String plaintext,String charset) throws Exception {
return encode(plaintext,charset).toString();
}
}
分页
public static Map<String, Object> PageList(int pagenum, List<?> objs, ITranPageObj tran) {
Map<String, Object> pageobj = new HashMap<String, Object>();
List<Object> resultList = new ArrayList<Object>(); if (objs.size() > pagenum * PAGE_SIZE) {
for (int i = (pagenum - 1) * PAGE_SIZE; i < pagenum * PAGE_SIZE; i++) {
Object o = objs.get(i);
if (tran != null) {
o = tran.tran(o);
}
resultList.add(o);
}
} else {
for (int i = (pagenum - 1) * PAGE_SIZE; i < objs.size(); i++) {
Object o = objs.get(i);
if (tran != null) {
o = tran.tran(o);
}
resultList.add(o);
}
} int pages = objs.size() / PAGE_SIZE;
if ((objs.size() % PAGE_SIZE) != 0) {
pages++;
}
int previousPage = (pagenum - 1 != 0) ? pagenum - 1 : 1;
int nextPage = pagenum >= pages ? pages : pagenum + 1; StringBuffer bufBarContent = new StringBuffer(2046);
bufBarContent.append("共 ").append(objs.size()).append(
" 条记录 每页 ").append(PAGE_SIZE).append(
" 条 共 ").append(pages).append(
" 页 第 ").append(pagenum).append(
" 页 ");
if (pagenum > 1) {
bufBarContent.append("<a href=\"javascript:go(1)\">首页</a>|");
bufBarContent.append("<a href=\"javascript:go(" + previousPage
+ ")\">上一页</a>|");
} else {
bufBarContent.append("首页|上一页|");
}
if (pagenum < pages) {
bufBarContent.append("<a href=\"javascript:go(" + nextPage
+ ")\">下一页</a>|");
bufBarContent.append("<a href=\"javascript:go("
+ (objs.size() / PAGE_SIZE + 1) + ")\">末页</a>");
} else {
bufBarContent.append("下一页|末页");
}
return pageobj;
}
private Hashtable cachedFile = new Hashtable();
/**
* constructor
* @param fileName
*/
public PropertiesTool(String fileName){
getPropertiesFromClasspath(fileName);
}
public void getPropertiesFromClasspath(String file){
ResourceBundle rb = ResourceBundle.getBundle(file);
Enumeration en = rb.getKeys();
while(en.hasMoreElements()){
String key = String.valueOf(en.nextElement());
cachedFile.put(key,rb.getString(key));
}
}
public String getValueByKey(String key){
if (cachedFile!=null && cachedFile.size()!=0 && key !=null) {
return String.valueOf(cachedFile.get(key));
}
return "no data found";
}
public int getDataCount(){
if (cachedFile!=null) {
return cachedFile.size();
}else{
return 0;
}
}
public List getKeys(){
List result = new ArrayList();
Enumeration en = cachedFile.keys();
if (cachedFile!=null) {
while (en.hasMoreElements()) {
result.add(en.nextElement());
}
}
return result;
}
//ShowColors.java
//Demonstrating Colors.//Java Core packages
import java.awt.*;
import java.awt.event.*;//java extension packages
import javax.swing.*;public class ShowColors extends JFrame{
//constructor sets window's title bar string and dimension
public ShowColors()
{
super("Using colors");
setSize(400,130);
setVisible(true);
}
//draw rectangles and Strings in different colors
public void paint(Graphics g)
{
//call superclass's paint method
super.paint(g);
//set new drawing colors using integers
g.setColor(new Color(255,0,0));
g.fillRect(25,25,100,20);
g.drawString("Current RGB:"+g.getColor(),130,40);
//set new drawing color using floats
g.setColor(new Color(0.0f,1.0f,0.0f));
g.fillRect(25,50,100,20);
g.drawString("Current RGB:"+g.getColor(),130,65);
//set new drawing color using static color objects
g.setColor(Color.blue);
g.fillRect(25,75,100,20);
g.drawString("Current RGB:"+g.getColor(),130,90);
//display individual RGB values
Color color = Color.magenta;
g.setColor(color);
g.fillRect(25,100,100,20);
g.drawString("RBG values:"+color.getRed()+","+color.getGreen()+","+color.getBlue(),130,115);
}
//excute application
public static void main(String args[])
{
ShowColors application =new ShowColors();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
}
}
//end class ShowColors