/**
* 将某个日期以固定格式转化成字符串
*
* @param date
* @return String
*/
public static String dateToStr(java.util.Date date)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = sdf.format(date);
return str;
}
/**
* 判断任意一个整数是否素数
*
* @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("");
}
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("\"", """, 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 = { "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));
}
}
}
/* * Db.java
Created on 2007年8月20日, 上午 8:37
*/
import java.io.*;
import java.sql.*;
import java.util.Properties;
public class Db {
private String driver;
private String url;
private String user;
private String password;
private Connection conn;
private Statement stm;
private ResultSet rs;
public Db(){
this("DBConf.properties");
}
public Db(String conf) {
loadProperties(conf);
setConn();
}
public Connection getConn(){
return this.conn;
}
//handle the properties file to get the informations for connection
private void loadProperties(String conf){
Properties props = new Properties();
try {
props.load(new FileInputStream(conf));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
this.driver = props.getProperty("driver");
this.url = props.getProperty("url");
this.user = props.getProperty("user");
this.password = props.getProperty("password");
}
//implement the Connection
private void setConn(){
try {
Class.forName(driver);
this.conn = DriverManager.getConnection(url,user,password);
} catch(ClassNotFoundException classnotfoundexception) {
classnotfoundexception.printStackTrace();
System.err.println("db: " + classnotfoundexception.getMessage());
} catch(SQLException sqlexception) {
System.err.println("db.getconn(): " + sqlexception.getMessage());
}
}
public void doInsert(String sql) {
try {
Statement statement = conn.createStatement();
int i = stm.executeUpdate(sql);
} catch(SQLException sqlexception) {
System.err.println("db.executeInset:" + sqlexception.getMessage());
}
}
public void doDelete(String sql) {
try {
stm = conn.createStatement();
int i = stm.executeUpdate(sql);
} catch(SQLException sqlexception) {
System.err.println("db.executeDelete:" + sqlexception.getMessage());
}
}
public void doUpdate(String sql) {
try {
stm = conn.createStatement();
int i = stm.executeUpdate(sql);
} catch(SQLException sqlexception) {
System.err.println("db.executeUpdate:" + sqlexception.getMessage());
}
}
public ResultSet doSelect(String sql) {
try {
stm = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY);
rs = stm.executeQuery(sql);
} catch(SQLException sqlexception) {
System.err.println("db.executeQuery: " + sqlexception.getMessage());
}
return rs;
}
public static void main(String[] args){
try{
Db db = new Db();
Connection conn = db.getConn();
if(conn != null && !conn.isClosed()) {
System.out.println("連結成功");
ResultSet rs = db.doSelect("select * from content");
while(rs.next()){
System.out.println(rs.getString(1)+":"+rs.getString(2)+":"+rs.getString(3));
}
rs.close();
conn.close();
}
}catch(SQLException e) {
e.printStackTrace();
}
}
}
/**
* 人民币转成大写
*
* @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
*/
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);
}
/**
* 设置JSpinner的编辑属性
* @param spinner 目标JSpinner
* @param isAllowInvalid 是否允许输入非法值
* @param isEditable 是否允许编辑
*/
public static void setAllowsInvalid(JSpinner spinner, boolean isAllowInvalid, boolean isEditable)
{
JSpinner.NumberEditor editor = new JSpinner.NumberEditor(spinner, "#");
spinner.setEditor(editor);
JFormattedTextField tf = ((JSpinner.NumberEditor)spinner.getEditor()).getTextField();
tf.setEditable(isEditable);
DefaultFormatterFactory factory = (DefaultFormatterFactory)tf.getFormatterFactory();
NumberFormatter formatter = (NumberFormatter)factory.getDefaultFormatter();
formatter.setAllowsInvalid(isAllowInvalid);
}
/**
* 根据指定方法的参数去构造一个新的对象的拷贝并将他返回
* @param obj 原始对象
* @return 新对象
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SecurityException
* @throws IllegalArgumentException
*/
@SuppressWarnings("unchecked")
public static Object copy(Object obj) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException
{
//获得对象的类型
Class classType = obj.getClass();
//通过默认构造方法去创建一个新的对象,getConstructor的视其参数决定调用哪个构造方法
Object objectCopy = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});
//获得对象的所有属性
Field[] fields = classType.getDeclaredFields();
for(int i = 0; i < fields.length; i++)
{
//获取数组中对应的属性
Field field = fields[i];
String fieldName = field.getName();
String stringLetter = fieldName.substring(0, 1).toUpperCase();
//获得相应属性的getXXX和setXXX方法名称
String getName = "get" + stringLetter + fieldName.substring(1);
String setName = "set" + stringLetter + fieldName.substring(1);
//获取相应的方法
Method getMethod = classType.getMethod(getName, new Class[]{});
Method setMethod = classType.getMethod(setName, new Class[]{field.getType()});
//调用源对象的getXXX()方法
Object value = getMethod.invoke(obj, new Object[]{});
//调用拷贝对象的setXXX()方法
setMethod.invoke(objectCopy, new Object[]{value});
}
return objectCopy;
}
/**
*一个for循环打印九九乘法表
*/
public void nineNineMultiTable()
{
for (int i = 1,j = 1; j <= 9; i++) {
System.out.print(i+"*"+j+"="+i*j+" ");
if(i==j)
{
i=0;
j++;
System.out.println();
}
}
}
/**
* 写入日志
* filePath 日志文件的路径
* code 要写入日志文件的内容
*/
public static boolean print(String filePath,String code) {
try {
File tofile=new File(filePath);
FileWriter fw=new FileWriter(tofile,true);
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
System.out.println(getDate()+":"+code);
pw.println(getDate()+":"+code);
pw.close();
bw.close();
fw.close();
return true;
} catch (IOException e) {
return false;
}
}
/**
* 判断是不是合法手机
* 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;
}
}
}
字符串匹配的算法.
public String getMaxMatch(String a,String b) {
StringBuffer tmp = new StringBuffer();
String maxString = "";
int max = 0;
int len = 0;
char[] aArray = a.toCharArray();
char[] bArray = b.toCharArray();
int posA = 0;
int posB = 0;
while(posA<aArray.length-max) {
posB = 0;
while(posB<(bArray.length-max)) {
if(aArray[posA]==bArray[posB]) {
len = 1;
tmp = new StringBuffer();
tmp.append(aArray[posA]);
while((posA+len<aArray.length)&&(posB+len<bArray.length)&&(aArray[posA+len]==bArray[posB+len])) {
tmp.append(aArray[posA+len]);
len++;
}
if(len>max) {
max = len;
maxString = tmp.toString();
}
}
posB++;
}
posA++;
}
return maxString;
}
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DateUtil
{
/**
* 格式化日期
*
* @param dateStr
* 字符型日期
* @param format
* 格式
* @return 返回日期
*/
public static java.util.Date parseDate(String dateStr, String format)
{
java.util.Date date = null;
try
{
java.text.DateFormat df = new java.text.SimpleDateFormat(format);
String dt = dateStr.replaceAll("-", "/");
if ((!dt.equals("")) && (dt.length() < format.length()))
{
dt += format.substring(dt.length()).replaceAll("[YyMmDdHhSs]", "0");
}
date = (java.util.Date) df.parse(dt);
}
catch (Exception e)
{
}
return date;
}
/**
* @param dateStr
* @return Date
*/
public static java.util.Date parseDate(String dateStr)
{
return parseDate(dateStr, "yyyy/MM/dd");
}
/**
* 格式化输出日期
*
* @param date
* 日期
* @param format
* 格式
* @return 返回字符型日期
*/
public static String format(java.util.Date date, String format)
{
String result = "";
try
{
if (date != null)
{
java.text.DateFormat df = new java.text.SimpleDateFormat(format);
result = df.format(date);
}
}
catch (Exception e)
{
}
return result;
}
public static String format(java.util.Date date)
{
return format(date, "yyyy/MM/dd");
}
/**
* 返回年份
*
* @param date
* 日期
* @return 返回年份
*/
public static int getYear(java.util.Date date)
{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.YEAR);
}
/**
* 返回月份
*
* @param date
* 日期
* @return 返回月份
*/
public static int getMonth(java.util.Date date)
{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.MONTH) + 1;
}
/**
* 返回日份
*
* @param date
* 日期
* @return 返回日份
*/
public static int getDay(java.util.Date date)
{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.DAY_OF_MONTH);
}
/**
* 返回小时
*
* @param date
* 日期
* @return 返回小时
*/
public static int getHour(java.util.Date date)
{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.HOUR_OF_DAY);
}
/**
* 返回分钟
*
* @param date
* 日期
* @return 返回分钟
*/
public static int getMinute(java.util.Date date)
{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.MINUTE);
}
/**
* 返回秒钟
*
* @param date
* 日期
* @return 返回秒钟
*/
public static int getSecond(java.util.Date date)
{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.SECOND);
}
/**
* 返回毫秒
*
* @param date
* 日期
* @return 返回毫秒
*/
public static long getMillis(java.util.Date date)
{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.getTimeInMillis();
}
/**
* 返回字符型日期
*
* @param date
* 日期
* @return 返回字符型日期
*/
public static String getDate(java.util.Date date)
{
return format(date, "yyyy/MM/dd");
}
/**
* 返回字符型时间
*
* @param date
* 日期
* @return 返回字符型时间
*/
public static String getTime(java.util.Date date)
{
return format(date, "HH:mm:ss");
}
/**
* 返回字符型日期时间
*
* @param date
* 日期
* @return 返回字符型日期时间
*/
public static String getDateTime(java.util.Date date)
{
return format(date, "yyyy/MM/dd HH:mm:ss");
}
/**
* 日期相加
*
* @param date
* 日期
* @param day
* 天数
* @return 返回相加后的日期
*/
public static java.util.Date addDate(java.util.Date date, int day)
{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTimeInMillis(getMillis(date) + ((long) day) * 24 * 3600 * 1000);
return c.getTime();
}
/**
* 日期相减
*
* @param date
* 日期
* @param date1
* 日期
* @return 返回相减后的日期
*/
public static int diffDate(java.util.Date date, java.util.Date date1)
{
return (int) ((getMillis(date) - getMillis(date1)) / (24 * 3600 * 1000));
}
/**
* 取得指定月份的第一天
*
* @param strdate
* String
* @return String
*/
public static String getMonthBegin(String strdate)
{
java.util.Date date = parseDate(strdate);
return format(date, "yyyy-MM") + "-01";
}
/**
* 取得指定月份的最后一天
*
* @param strdate
* String
* @return String
*/
public static String getMonthEnd(String strdate)
{
java.util.Date date = parseDate(getMonthBegin(strdate));
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.DAY_OF_YEAR, -1);
return formatDate(calendar.getTime());
}
/**
* 常用的格式化日期
*
* @param date
* Date
* @return String
*/
public static String formatDate(java.util.Date date)
{
return formatDateByFormat(date, "yyyy-MM-dd");
}
/**
* 以指定的格式来格式化日期
*
* @param date
* Date
* @param format
* String
* @return String
*/
public static String formatDateByFormat(java.util.Date date, String format)
{
String result = "";
if (date != null)
{
try
{
SimpleDateFormat sdf = new SimpleDateFormat(format);
result = sdf.format(date);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
return result;
}
}
* 将某个日期以固定格式转化成字符串
*
* @param date
* @return String
*/
public static String dateToStr(java.util.Date date)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = sdf.format(date);
return str;
}
/**
* 判断任意一个整数是否素数
*
* @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("");
}
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("\"", """, 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 = { "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));
}
}
}
/* * Db.java
Created on 2007年8月20日, 上午 8:37
*/
import java.io.*;
import java.sql.*;
import java.util.Properties;
public class Db {
private String driver;
private String url;
private String user;
private String password;
private Connection conn;
private Statement stm;
private ResultSet rs;
public Db(){
this("DBConf.properties");
}
public Db(String conf) {
loadProperties(conf);
setConn();
}
public Connection getConn(){
return this.conn;
}
//handle the properties file to get the informations for connection
private void loadProperties(String conf){
Properties props = new Properties();
try {
props.load(new FileInputStream(conf));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
this.driver = props.getProperty("driver");
this.url = props.getProperty("url");
this.user = props.getProperty("user");
this.password = props.getProperty("password");
}
//implement the Connection
private void setConn(){
try {
Class.forName(driver);
this.conn = DriverManager.getConnection(url,user,password);
} catch(ClassNotFoundException classnotfoundexception) {
classnotfoundexception.printStackTrace();
System.err.println("db: " + classnotfoundexception.getMessage());
} catch(SQLException sqlexception) {
System.err.println("db.getconn(): " + sqlexception.getMessage());
}
}
public void doInsert(String sql) {
try {
Statement statement = conn.createStatement();
int i = stm.executeUpdate(sql);
} catch(SQLException sqlexception) {
System.err.println("db.executeInset:" + sqlexception.getMessage());
}
}
public void doDelete(String sql) {
try {
stm = conn.createStatement();
int i = stm.executeUpdate(sql);
} catch(SQLException sqlexception) {
System.err.println("db.executeDelete:" + sqlexception.getMessage());
}
}
public void doUpdate(String sql) {
try {
stm = conn.createStatement();
int i = stm.executeUpdate(sql);
} catch(SQLException sqlexception) {
System.err.println("db.executeUpdate:" + sqlexception.getMessage());
}
}
public ResultSet doSelect(String sql) {
try {
stm = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY);
rs = stm.executeQuery(sql);
} catch(SQLException sqlexception) {
System.err.println("db.executeQuery: " + sqlexception.getMessage());
}
return rs;
}
public static void main(String[] args){
try{
Db db = new Db();
Connection conn = db.getConn();
if(conn != null && !conn.isClosed()) {
System.out.println("連結成功");
ResultSet rs = db.doSelect("select * from content");
while(rs.next()){
System.out.println(rs.getString(1)+":"+rs.getString(2)+":"+rs.getString(3));
}
rs.close();
conn.close();
}
}catch(SQLException e) {
e.printStackTrace();
}
}
}
/**
* 人民币转成大写
*
* @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
*/
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);
}
/**
* 设置JSpinner的编辑属性
* @param spinner 目标JSpinner
* @param isAllowInvalid 是否允许输入非法值
* @param isEditable 是否允许编辑
*/
public static void setAllowsInvalid(JSpinner spinner, boolean isAllowInvalid, boolean isEditable)
{
JSpinner.NumberEditor editor = new JSpinner.NumberEditor(spinner, "#");
spinner.setEditor(editor);
JFormattedTextField tf = ((JSpinner.NumberEditor)spinner.getEditor()).getTextField();
tf.setEditable(isEditable);
DefaultFormatterFactory factory = (DefaultFormatterFactory)tf.getFormatterFactory();
NumberFormatter formatter = (NumberFormatter)factory.getDefaultFormatter();
formatter.setAllowsInvalid(isAllowInvalid);
}
/**
* 根据指定方法的参数去构造一个新的对象的拷贝并将他返回
* @param obj 原始对象
* @return 新对象
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SecurityException
* @throws IllegalArgumentException
*/
@SuppressWarnings("unchecked")
public static Object copy(Object obj) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException
{
//获得对象的类型
Class classType = obj.getClass();
//通过默认构造方法去创建一个新的对象,getConstructor的视其参数决定调用哪个构造方法
Object objectCopy = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});
//获得对象的所有属性
Field[] fields = classType.getDeclaredFields();
for(int i = 0; i < fields.length; i++)
{
//获取数组中对应的属性
Field field = fields[i];
String fieldName = field.getName();
String stringLetter = fieldName.substring(0, 1).toUpperCase();
//获得相应属性的getXXX和setXXX方法名称
String getName = "get" + stringLetter + fieldName.substring(1);
String setName = "set" + stringLetter + fieldName.substring(1);
//获取相应的方法
Method getMethod = classType.getMethod(getName, new Class[]{});
Method setMethod = classType.getMethod(setName, new Class[]{field.getType()});
//调用源对象的getXXX()方法
Object value = getMethod.invoke(obj, new Object[]{});
//调用拷贝对象的setXXX()方法
setMethod.invoke(objectCopy, new Object[]{value});
}
return objectCopy;
}
/**
*一个for循环打印九九乘法表
*/
public void nineNineMultiTable()
{
for (int i = 1,j = 1; j <= 9; i++) {
System.out.print(i+"*"+j+"="+i*j+" ");
if(i==j)
{
i=0;
j++;
System.out.println();
}
}
}
/**
* 写入日志
* filePath 日志文件的路径
* code 要写入日志文件的内容
*/
public static boolean print(String filePath,String code) {
try {
File tofile=new File(filePath);
FileWriter fw=new FileWriter(tofile,true);
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
System.out.println(getDate()+":"+code);
pw.println(getDate()+":"+code);
pw.close();
bw.close();
fw.close();
return true;
} catch (IOException e) {
return false;
}
}
/**
* 判断是不是合法手机
* 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;
}
}
}
字符串匹配的算法.
public String getMaxMatch(String a,String b) {
StringBuffer tmp = new StringBuffer();
String maxString = "";
int max = 0;
int len = 0;
char[] aArray = a.toCharArray();
char[] bArray = b.toCharArray();
int posA = 0;
int posB = 0;
while(posA<aArray.length-max) {
posB = 0;
while(posB<(bArray.length-max)) {
if(aArray[posA]==bArray[posB]) {
len = 1;
tmp = new StringBuffer();
tmp.append(aArray[posA]);
while((posA+len<aArray.length)&&(posB+len<bArray.length)&&(aArray[posA+len]==bArray[posB+len])) {
tmp.append(aArray[posA+len]);
len++;
}
if(len>max) {
max = len;
maxString = tmp.toString();
}
}
posB++;
}
posA++;
}
return maxString;
}
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DateUtil
{
/**
* 格式化日期
*
* @param dateStr
* 字符型日期
* @param format
* 格式
* @return 返回日期
*/
public static java.util.Date parseDate(String dateStr, String format)
{
java.util.Date date = null;
try
{
java.text.DateFormat df = new java.text.SimpleDateFormat(format);
String dt = dateStr.replaceAll("-", "/");
if ((!dt.equals("")) && (dt.length() < format.length()))
{
dt += format.substring(dt.length()).replaceAll("[YyMmDdHhSs]", "0");
}
date = (java.util.Date) df.parse(dt);
}
catch (Exception e)
{
}
return date;
}
/**
* @param dateStr
* @return Date
*/
public static java.util.Date parseDate(String dateStr)
{
return parseDate(dateStr, "yyyy/MM/dd");
}
/**
* 格式化输出日期
*
* @param date
* 日期
* @param format
* 格式
* @return 返回字符型日期
*/
public static String format(java.util.Date date, String format)
{
String result = "";
try
{
if (date != null)
{
java.text.DateFormat df = new java.text.SimpleDateFormat(format);
result = df.format(date);
}
}
catch (Exception e)
{
}
return result;
}
public static String format(java.util.Date date)
{
return format(date, "yyyy/MM/dd");
}
/**
* 返回年份
*
* @param date
* 日期
* @return 返回年份
*/
public static int getYear(java.util.Date date)
{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.YEAR);
}
/**
* 返回月份
*
* @param date
* 日期
* @return 返回月份
*/
public static int getMonth(java.util.Date date)
{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.MONTH) + 1;
}
/**
* 返回日份
*
* @param date
* 日期
* @return 返回日份
*/
public static int getDay(java.util.Date date)
{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.DAY_OF_MONTH);
}
/**
* 返回小时
*
* @param date
* 日期
* @return 返回小时
*/
public static int getHour(java.util.Date date)
{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.HOUR_OF_DAY);
}
/**
* 返回分钟
*
* @param date
* 日期
* @return 返回分钟
*/
public static int getMinute(java.util.Date date)
{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.MINUTE);
}
/**
* 返回秒钟
*
* @param date
* 日期
* @return 返回秒钟
*/
public static int getSecond(java.util.Date date)
{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.get(java.util.Calendar.SECOND);
}
/**
* 返回毫秒
*
* @param date
* 日期
* @return 返回毫秒
*/
public static long getMillis(java.util.Date date)
{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(date);
return c.getTimeInMillis();
}
/**
* 返回字符型日期
*
* @param date
* 日期
* @return 返回字符型日期
*/
public static String getDate(java.util.Date date)
{
return format(date, "yyyy/MM/dd");
}
/**
* 返回字符型时间
*
* @param date
* 日期
* @return 返回字符型时间
*/
public static String getTime(java.util.Date date)
{
return format(date, "HH:mm:ss");
}
/**
* 返回字符型日期时间
*
* @param date
* 日期
* @return 返回字符型日期时间
*/
public static String getDateTime(java.util.Date date)
{
return format(date, "yyyy/MM/dd HH:mm:ss");
}
/**
* 日期相加
*
* @param date
* 日期
* @param day
* 天数
* @return 返回相加后的日期
*/
public static java.util.Date addDate(java.util.Date date, int day)
{
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTimeInMillis(getMillis(date) + ((long) day) * 24 * 3600 * 1000);
return c.getTime();
}
/**
* 日期相减
*
* @param date
* 日期
* @param date1
* 日期
* @return 返回相减后的日期
*/
public static int diffDate(java.util.Date date, java.util.Date date1)
{
return (int) ((getMillis(date) - getMillis(date1)) / (24 * 3600 * 1000));
}
/**
* 取得指定月份的第一天
*
* @param strdate
* String
* @return String
*/
public static String getMonthBegin(String strdate)
{
java.util.Date date = parseDate(strdate);
return format(date, "yyyy-MM") + "-01";
}
/**
* 取得指定月份的最后一天
*
* @param strdate
* String
* @return String
*/
public static String getMonthEnd(String strdate)
{
java.util.Date date = parseDate(getMonthBegin(strdate));
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.DAY_OF_YEAR, -1);
return formatDate(calendar.getTime());
}
/**
* 常用的格式化日期
*
* @param date
* Date
* @return String
*/
public static String formatDate(java.util.Date date)
{
return formatDateByFormat(date, "yyyy-MM-dd");
}
/**
* 以指定的格式来格式化日期
*
* @param date
* Date
* @param format
* String
* @return String
*/
public static String formatDateByFormat(java.util.Date date, String format)
{
String result = "";
if (date != null)
{
try
{
SimpleDateFormat sdf = new SimpleDateFormat(format);
result = sdf.format(date);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
return result;
}
}