- 浏览: 159822 次
- 性别:
- 来自: 北京
最新评论
-
liuzl121:
收藏下 写楼主的转载
[转]如何操作Cookie -
smesoft:
ding[b][/b]
J2EE面试题集锦(附答案) -
ksmjava:
好,非常有用的CSS文章哦,
简单的CSS改进网站设计三个技巧 -
mlitest:
图1去哪儿了?
UML 序列图简介 为用例逻辑建模 -
sunwenran:
在Java开发中使用的RPC编程接口:RMI、XML-RPC、 ...
Java RPC通信机制之RMI
/**
* 将某个日期以固定格式转化成字符串
*
* @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("");
}
常用的java函数(二) 常用字符串处理
/**
* 分割字符串
*
* @param str String 原始字符串
* @param splitsign String 分隔符
* @return String[] 分割后的字符串数组
*/
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;
}
/**
* 全角字符转半角字符
*
* @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);
}
//过滤特殊字符
public static String encoding(String src){
if (src==null)
return "";
StringBuilder result=new StringBuilder();
if (src!=null){
src=src.trim();
for (int pos=0;pos<src.length();pos++){
switch(src.charAt(pos)){
case '\"':result.append(""");break;
case '<':result.append("<");break;
case '>':result.append(">");break;
case '\'':result.append("'");break;
case '&':result.append("&");break;
case '%':result.append("&pc;");break;
case '_':result.append("&ul;");break;
case '#':result.append("&shap;");break;
case '?':result.append("&ques;");break;
default:result.append(src.charAt(pos));break;
}
}
}
return result.toString();
}
//反过滤特殊字符
public static String decoding(String src){
if (src==null)
return "";
String result=src;
result=result.replace(""", "\"").replace("'", "\'");
result=result.replace("<", "<").replace(">", ">");
result=result.replace("&", "&");
result=result.replace("&pc;", "%").replace("&ul", "_");
result=result.replace("&shap;", "#").replace("&ques", "?");
return result;
}
/**
*判断任意一个整数是否素数
*@paramn
*@return boolean
*/
public boolean isPrimes(int n)
{
for (int i = 2; i <= Math.sqrt(n); i++) {
if(n%i==0)
{
return false;
}
}
return true;
}
常用的java函数(三)数据库连接
/* * 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();
}
}
}
常用的java函数(四)中文转拼音
/**
* <p>
* Title:
* Description:中文转换为拼音
* @version 1.0
*/
public class ChineseSpelling {
private static int[] pyvalue = new int[] { -20319, -20317, -20304, -20295, -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036, -20032, -20026, -20002, -19990, -19986, -19982, -19976, -19805, -19784, -19775, -19774, -19763, -19756, -19751, -19746, -19741, -19739, -19728, -19725, -19715, -19540, -19531, -19525, -19515, -19500, -19484, -19479, -19467, -19289, -19288, -19281, -19275, -19270, -19263, -19261, -19249, -19243, -19242, -19238, -19235, -19227, -19224, -19218, -19212, -19038, -19023, -19018, -19006, -19003, -18996, -18977, -18961, -18952, -18783, -18774, -18773, -18763, -18756, -18741, -18735, -18731, -18722, -18710, -18697, -18696, -18526, -18518, -18501, -18490, -18478, -18463, -18448, -18447, -18446, -18239, -18237, -18231, -18220, -18211, -18201, -18184, -18183,
-18181, -18012, -17997, -17988, -17970, -17964, -17961, -17950, -17947, -17931, -17928, -17922, -17759, -17752, -17733, -17730, -17721, -17703, -17701, -17697, -17692, -17683, -17676, -17496, -17487, -17482, -17468, -17454, -17433, -17427, -17417, -17202, -17185, -16983, -16970, -16942, -16915, -16733, -16708, -16706, -16689, -16664, -16657, -16647, -16474, -16470, -16465, -16459, -16452, -16448, -16433, -16429, -16427, -16423, -16419, -16412, -16407, -16403, -16401, -16393, -16220, -16216, -16212, -16205, -16202, -16187, -16180, -16171, -16169, -16158, -16155, -15959, -15958, -15944, -15933, -15920, -15915, -15903, -15889, -15878, -15707, -15701, -15681, -15667, -15661, -15659, -15652, -15640, -15631, -15625, -15454, -15448, -15436, -15435, -15419, -15416, -15408, -15394,
-15385, -15377, -15375, -15369, -15363, -15362, -15183, -15180, -15165, -15158, -15153, -15150, -15149, -15144, -15143, -15141, -15140, -15139, -15128, -15121, -15119, -15117, -15110, -15109, -14941, -14937, -14933, -14930, -14929, -14928, -14926, -14922, -14921, -14914, -14908, -14902, -14894, -14889, -14882, -14873, -14871, -14857, -14678, -14674, -14670, -14668, -14663, -14654, -14645, -14630, -14594, -14429, -14407, -14399, -14384, -14379, -14368, -14355, -14353, -14345, -14170, -14159, -14151, -14149, -14145, -14140, -14137, -14135, -14125, -14123, -14122, -14112, -14109, -14099, -14097, -14094, -14092, -14090, -14087, -14083, -13917, -13914, -13910, -13907, -13906, -13905, -13896, -13894, -13878, -13870, -13859, -13847, -13831, -13658, -13611, -13601, -13406, -13404,
-13400, -13398, -13395, -13391, -13387, -13383, -13367, -13359, -13356, -13343, -13340, -13329, -13326, -13318, -13147, -13138, -13120, -13107, -13096, -13095, -13091, -13076, -13068, -13063, -13060, -12888, -12875, -12871, -12860, -12858, -12852, -12849, -12838, -12831, -12829, -12812, -12802, -12607, -12597, -12594, -12585, -12556, -12359, -12346, -12320, -12300, -12120, -12099, -12089, -12074, -12067, -12058, -12039, -11867, -11861, -11847, -11831, -11798, -11781, -11604, -11589, -11536, -11358, -11340, -11339, -11324, -11303, -11097, -11077, -11067, -11055, -11052, -11045, -11041, -11038, -11024, -11020, -11019, -11018, -11014, -10838, -10832, -10815, -10800, -10790, -10780, -10764, -10587, -10544, -10533, -10519, -10331, -10329, -10328, -10322, -10315, -10309, -10307,
-10296, -10281, -10274, -10270, -10262, -10260, -10256, -10254 };
private static String[] pystr = new String[] { "a", "ai", "an", "ang", "ao", "ba", "bai", "ban", "bang", "bao", "bei", "ben", "beng", "bi", "bian", "biao", "bie", "bin", "bing", "bo", "bu", "ca", "cai", "can", "cang", "cao", "ce", "ceng", "cha", "chai", "chan", "chang", "chao", "che", "chen", "cheng", "chi", "chong", "chou", "chu", "chuai", "chuan", "chuang", "chui", "chun", "chuo", "ci", "cong", "cou", "cu", "cuan", "cui", "cun", "cuo", "da", "dai", "dan", "dang", "dao", "de", "deng", "di", "dian", "diao", "die", "ding", "diu", "dong", "dou", "du", "duan", "dui", "dun", "duo", "e", "en", "er", "fa", "fan", "fang", "fei", "fen", "feng", "fo", "fou", "fu", "ga", "gai", "gan", "gang", "gao", "ge", "gei", "gen", "geng", "gong", "gou", "gu", "gua", "guai", "guan", "guang", "gui", "gun",
"guo", "ha", "hai", "han", "hang", "hao", "he", "hei", "hen", "heng", "hong", "hou", "hu", "hua", "huai", "huan", "huang", "hui", "hun", "huo", "ji", "jia", "jian", "jiang", "jiao", "jie", "jin", "jing", "jiong", "jiu", "ju", "juan", "jue", "jun", "ka", "kai", "kan", "kang", "kao", "ke", "ken", "keng", "kong", "kou", "ku", "kua", "kuai", "kuan", "kuang", "kui", "kun", "kuo", "la", "lai", "lan", "lang", "lao", "le", "lei", "leng", "li", "lia", "lian", "liang", "liao", "lie", "lin", "ling", "liu", "long", "lou", "lu", "lv", "luan", "lue", "lun", "luo", "ma", "mai", "man", "mang", "mao", "me", "mei", "men", "meng", "mi", "mian", "miao", "mie", "min", "ming", "miu", "mo", "mou", "mu", "na", "nai", "nan", "nang", "nao", "ne", "nei", "nen", "neng", "ni", "nian", "niang", "niao",
"nie", "nin", "ning", "niu", "nong", "nu", "nv", "nuan", "nue", "nuo", "o", "ou", "pa", "pai", "pan", "pang", "pao", "pei", "pen", "peng", "pi", "pian", "piao", "pie", "pin", "ping", "po", "pu", "qi", "qia", "qian", "qiang", "qiao", "qie", "qin", "qing", "qiong", "qiu", "qu", "quan", "que", "qun", "ran", "rang", "rao", "re", "ren", "reng", "ri", "rong", "rou", "ru", "ruan", "rui", "run", "ruo", "sa", "sai", "san", "sang", "sao", "se", "sen", "seng", "sha", "shai", "shan", "shang", "shao", "she", "shen", "sheng", "shi", "shou", "shu", "shua", "shuai", "shuan", "shuang", "shui", "shun", "shuo", "si", "song", "sou", "su", "suan", "sui", "sun", "suo", "ta", "tai", "tan", "tang", "tao", "te", "teng", "ti", "tian", "tiao", "tie", "ting", "tong", "tou", "tu", "tuan", "tui", "tun",
"tuo", "wa", "wai", "wan", "wang", "wei", "wen", "weng", "wo", "wu", "xi", "xia", "xian", "xiang", "xiao", "xie", "xin", "xing", "xiong", "xiu", "xu", "xuan", "xue", "xun", "ya", "yan", "yang", "yao", "ye", "yi", "yin", "ying", "yo", "yong", "you", "yu", "yuan", "yue", "yun", "za", "zai", "zan", "zang", "zao", "ze", "zei", "zen", "zeng", "zha", "zhai", "zhan", "zhang", "zhao", "zhe", "zhen", "zheng", "zhi", "zhong", "zhou", "zhu", "zhua", "zhuai", "zhuan", "zhuang", "zhui", "zhun", "zhuo", "zi", "zong", "zou", "zu", "zuan", "zui", "zun", "zuo" };
private StringBuilder buffer;
private String resource;
private static ChineseSpelling chineseSpelling = new ChineseSpelling();
public static ChineseSpelling getInstance() {
return chineseSpelling;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
private int getChsAscii(String chs) {
int asc = 0;
try {
byte[] bytes = chs.getBytes("gb2312");
if (bytes == null || bytes.length > 2 || bytes.length <= 0) { // 错误
// log
throw new RuntimeException("illegal resource string");
// System.out.println("error");
}
if (bytes.length == 1) { // 英文字符
asc = bytes[0];
}
if (bytes.length == 2) { // 中文字符
int hightByte = 256 + bytes[0];
int lowByte = 256 + bytes[1];
asc = (256 * hightByte + lowByte) - 256 * 256;
}
} catch (Exception e) {
System.out.println("ERROR:ChineseSpelling.class-getChsAscii(String chs)" + e);
// e.printStackTrace();
}
return asc;
}
public String convert(String str) {
String result = null;
int ascii = getChsAscii(str);
// System.out.println(ascii);
if (ascii > 0 && ascii < 160) {
result = String.valueOf((char) ascii);
} else {
for (int i = (pyvalue.length - 1); i >= 0; i--) {
if (pyvalue[i] <= ascii) {
result = pystr[i];
break;
}
}
}
return result;
}
public String getSelling(String chs) {
String key, value;
buffer = new StringBuilder();
for (int i = 0; i < chs.length(); i++) {
key = chs.substring(i, i + 1);
if (key.getBytes().length == 2) {
value = (String) convert(key);
if (value == null) {
value = "unknown";
}
} else {
value = key;
}
buffer.append(value);
}
return buffer.toString();
}
public String getSpelling() {
return this.getSelling(this.getResource());
}
public static void main(String[] args) {
// ChineseSpelling finder = new ChineseSpelling();
ChineseSpelling finder = ChineseSpelling.getInstance();
finder.setResource("中文字符");
System.out.println(finder.getSpelling());
System.out.println(finder.getSelling("英文字符Eng"));
}
}
常用的java函数(五)人民币转成大写
/**
* 人民币转成大写
*
* @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; // 返回正确表示
常用的java函数(六)异常处理类
/**
* (#)ThrowableManager.java 1.0 Apr 10, 2008
*
* Copyright 2007- wargrey , Inc. All rights are reserved.
*/
package net.wargrey.application;
import java.awt.Component;
import javax.swing.JOptionPane;
/**
* This class <code>ExceptionManager</code> and its subclasses are a form of
* <code>Exception</code>. It is used to wrap all the <code>Throwable</code> instances
* and handle them in a unified way. It will show the information which consists of
* StackTraces and Messages by using JOptionPanel.
*
* @author Estelle
* @version 1.0
* @see java.lang.Exception
* @since jdk 1.5
*/
public class ExceptionManager extends Exception {
/**
* This field <code>alerter</code> is used to show the information the Class offered.
*
* @see javax.swing.JOptionPane
*/
private JOptionPane alerter;
/**
* This static method create an instance of the ExceptionManager by invoking the
* constructor <code>ExceptionManager(String msg)</code>.
*
* @param msg The message will pass the specified constructor
* @return An instance of the ExceptionManager created by invoking the constructor
* <code>ExceptionManager(String msg)</code>.
*/
public static ExceptionManager wrap(String msg){
return new ExceptionManager(msg);
}
/**
* This static method create an instance of the ExceptionManager by invoking the
* constructor <code>ExceptionManager(Throwable throwable)</code>.
*
* @param throwable The cause will pass the specified constructor
* @return An instance of the ExceptionManager created by invoking the constructor
* <code>ExceptionManager(Throwable throwable)</code>.
*/
public static ExceptionManager wrap(Throwable throwable){
return new ExceptionManager(throwable);
}
/**
* This static method create an instance of the ExceptionManager by invoking the
* constructor <code>ExceptionManager(String msg,Throwable throwable)</code>.
*
* @param msg The message will pass the specified constructor
* @param throwable The cause will pass the specified constructor
* @return An instance of the ExceptionManager created by invoking the constructor
* <code>ExceptionManager(String msg, Throwable throwable)</code>
*/
public static ExceptionManager wrap(String msg,Throwable throwable){
return new ExceptionManager(msg,throwable);
}
/**
* Constructs a new instance with the specified detail message. The concrete handler
* is its super class. This constructor always used to construct a custom exception
* not wrapping the exist exception.
*
* @param msg the detail message which is the part of the information will be
* shown.
*/
public ExceptionManager(String msg){
super(msg);
}
/**
* Constructs a new instance with the specified detail cause. The concrete handler
* is its super class. This constructor always used to wrap an exist exception.
*
* @param throwable the cause which has been caught. It's detail message and
* stacktrace are the parts the information will be shown.
*/
public ExceptionManager(Throwable throwable){
super(throwable);
}
/**
* Constructs a new instance with the specified detail message and cause. The
* concrete handler is its super class. This constructor always used to construct
* an exception wrapping the exist exception but requires a custom message.
*
* @param msg the detail message which is the part of the information will
* be shown.
* @param throwable the cause which has been caught. It's stacktrace is the parts
* the information will be shown.
*/
public ExceptionManager(String msg,Throwable throwable){
super(msg,throwable);
}
/**
* Show the information with everything is default.
*/
public synchronized void alert(){
alert((Component)null);
}
/**
* Show the information in a dialog with the specified title
* "ThrowableManager Alerter". The dialog belongs to the given component which
* default is the screen.
*
* @param parent The component cause the exception.
*/
public synchronized void alert(Component parent){
alert(parent,"ThrowableManager Alerter");
}
/**
* Show the information in a dialog with the specified title.
*
* @param title The title of the dialog.
*/
public synchronized void alert(String title){
alert((Component)null,title);
}
/**
* Show the information in a dialog which has the specified title and belongs to the
* specified component.
*
* @param parent The component cause the exception.
* @param title The title of the dialog.
*/
public synchronized void alert(Component parent,String title){
StringBuilder errorMessage=new StringBuilder();
errorMessage.append(this.toString());
for (StackTraceElement st:((this.getCause()==null)?this:this.getCause()).getStackTrace()){
errorMessage.append("\n\t at ");
errorMessage.append(st.toString());
}
alerter.showMessageDialog(parent, errorMessage, title ,JOptionPane.ERROR_MESSAGE);
}
}
常用的java函数(七)各类数据库连接
MySQL:
String Driver="com.mysql.jdbc.Driver"; //驱动程序
String URL="jdbc:mysql://localhost:3306/db_name"; //连接的URL,db_name为数据库名
String Username="username"; //用户名
String Password="password"; //密码
Class.forName(Driver).new Instance();
Connection con=DriverManager.getConnection(URL,Username,Password);
Microsoft SQL Server 2.0驱动(3个jar的那个):
String Driver="com.microsoft.jdbc.sqlserver.SQLServerDriver"; //连接SQL数据库的方法
String URL="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_name"; //db_name为数据库名
String Username="username"; //用户名
String Password="password"; //密码
Class.forName(Driver).new Instance(); //加载数据可驱动
Connection con=DriverManager.getConnection(URL,UserName,Password); //
Microsoft SQL Server 3.0驱动(1个jar的那个): // 老紫竹完善
String Driver="com.microsoft.sqlserver.jdbc.SQLServerDriver"; //连接SQL数据库的方法
String URL="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_name"; //db_name为数据库名
String Username="username"; //用户名
String Password="password"; //密码
Class.forName(Driver).new Instance(); //加载数据可驱动
Connection con=DriverManager.getConnection(URL,UserName,Password); //
Sysbase:
String Driver="com.sybase.jdbc.SybDriver"; //驱动程序
String URL="jdbc:Sysbase://localhost:5007/db_name"; //db_name为数据可名
String Username="username"; //用户名
String Password="password"; //密码
Class.forName(Driver).newInstance();
Connection con=DriverManager.getConnection(URL,Username,Password);
Oracle(用thin模式):
String Driver="oracle.jdbc.driver.OracleDriver"; //连接数据库的方法
String URL="jdbc:oracle:thin:@loaclhost:1521:orcl"; //orcl为数据库的SID
String Username="username"; //用户名
String Password="password"; //密码
Class.forName(Driver).newInstance(); //加载数据库驱动
Connection con=DriverManager.getConnection(URL,Username,Password);
PostgreSQL:
String Driver="org.postgresql.Driver"; //连接数据库的方法
String URL="jdbc:postgresql://localhost/db_name"; //db_name为数据可名
String Username="username"; //用户名
String Password="password"; //密码
Class.forName(Driver).newInstance();
Connection con=DriverManager.getConnection(URL,Username,Password);
DB2:
String Driver="com.ibm.db2.jdbc.app.DB2.Driver"; //连接具有DB2客户端的Provider实例
//String Driver="com.ibm.db2.jdbc.net.DB2.Driver"; //连接不具有DB2客户端的Provider实例
String URL="jdbc:db2://localhost:5000/db_name"; //db_name为数据可名
String Username="username"; //用户名
String Password="password"; //密码
Class.forName(Driver).newInstance();
Connection con=DriverManager.getConnection(URL,Username,Password);
Informix:
String Driver="com.informix.jdbc.IfxDriver";
String URL="jdbc:Informix-sqli://localhost:1533/db_name:INFORMIXSER=myserver"; //db_name为数据可名
String Username="username"; //用户名
String Password="password"; //密码
Class.forName(Driver).newInstance();
Connection con=DriverManager.getConnection(URL,Username,Password);
JDBC-ODBC:
String Driver="sun.jdbc.odbc.JdbcOdbcDriver";
String URL="jdbc:odbc:dbsource"; //dbsource为数据源名
String Username="username"; //用户名
String Password="password"; //密码
Class.forName(Driver).newInstance();
Connection con=DriverManager.getConnection(URL,Username,Password);
常用的java函数(八)TXT转XML
/*
*txt转换xml
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.StringTokenizer;
public class TxtToXml {
private String strTxtFileName;
private String strXmlFileName;
public TxtToXml() {
strTxtFileName = new String();
strXmlFileName = new String();
}
public void createXml(String strTxt, String strXml) {
strTxtFileName = strTxt;
strXmlFileName = strXml;
String strTmp;
try {
BufferedReader inTxt = new BufferedReader(new FileReader(
strTxtFileName));
BufferedWriter outXml = new BufferedWriter(new FileWriter(
strXmlFileName));
outXml.write("<?xml version= \"1.0\" encoding=\"gb2312\"?>");
outXml.newLine();
outXml.write("<people>");
while ((strTmp = inTxt.readLine()) != null) {
StringTokenizer strToken = new StringTokenizer(strTmp, ",");
String arrTmp[];
arrTmp = new String[3];
for (int i = 0; i < 3; i++)
arrTmp[i] = new String("");
int index = 0;
outXml.newLine();
outXml.write(" <students>");
while (strToken.hasMoreElements()) {
strTmp = (String) strToken.nextElement();
strTmp = strTmp.trim();
arrTmp[index++] = strTmp;
}
outXml.newLine();
outXml.write(" <name>" + arrTmp[0] + "</name>");
outXml.newLine();
outXml.write(" <sex>" + arrTmp[1] + "</sex>");
outXml.newLine();
outXml.write(" <age>" + arrTmp[2] + "</age>");
outXml.newLine();
outXml.write(" </students>");
}
outXml.newLine();
outXml.write("</people>");
outXml.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String txtName = "testtxt.txt";
String xmlName = "testxml.xml";
TxtToXml thisClass = new TxtToXml();
thisClass.createXml(txtName, xmlName);
}
}
常用的java函数(九)时间计算函数
import java.text.DecimalFormat;
import java.util.Arrays;
/**
* 时间计算工具类
*/
public class Time {
/**
* 时间字段常量,表示“秒”
*/
public final static int SECOND = 0;
/**
* 时间字段常量,表示“分”
*/
public final static int MINUTE = 1;
/**
* 时间字段常量,表示“时”
*/
public final static int HOUR = 2;
/**
* 时间字段常量,表示“天”
*/
public final static int DAY = 3;
/**
* 各常量允许的最大值
*/
private final int[] maxFields = { 59, 59, 23, Integer.MAX_VALUE - 1 };
/**
* 各常量允许的最小值
*/
private final int[] minFields = { 0, 0, 0, Integer.MIN_VALUE };
/**
* 默认的字符串格式时间分隔符
*/
private String timeSeparator = ":";
/**
* 时间数据容器
*/
private int[] fields = new int[4];
/**
* 无参构造,将各字段置为 0
*/
public Time() {
this(0, 0, 0, 0);
}
/**
* 使用时、分构造一个时间
* @param hour 小时
* @param minute 分钟
*/
public Time(int hour, int minute) {
this(0, hour, minute, 0);
}
/**
* 使用时、分、秒构造一个时间
* @param hour 小时
* @param minute 分钟
* @param second 秒
*/
public Time(int hour, int minute, int second) {
this(0, hour, minute, second);
}
/**
* 使用一个字符串构造时间<br/>
* Time time = new Time("14:22:23");
* @param time 字符串格式的时间,默认采用“:”作为分隔符
*/
public Time(String time) {
this(time, null);
}
/**
* 使用天、时、分、秒构造时间,进行全字符的构造
* @param day 天
* @param hour 时
* @param minute 分
* @param second 秒
*/
public Time(int day, int hour, int minute, int second) {
set(DAY, day);
set(HOUR, hour);
set(MINUTE, minute);
set(SECOND, second);
}
/**
* 使用一个字符串构造时间,指定分隔符<br/>
* Time time = new Time("14-22-23", "-");
* @param time 字符串格式的时间
*/
public Time(String time, String timeSeparator) {
if(timeSeparator != null) {
setTimeSeparator(timeSeparator);
}
String pattern = patternQuote(this.timeSeparator);
String matcher = new StringBuffer()
.append("\\d+?").append(pattern)
.append("\\d+?").append(pattern)
.append("\\d+?")
.toString();
if(!time.matches(matcher)) {
throw new IllegalArgumentException(time + ", time format error, HH"
+ this.timeSeparator + "mm" + this.timeSeparator + "ss");
}
String[] times = time.split(pattern);
set(DAY, 0);
set(HOUR, Integer.parseInt(times[0]));
set(MINUTE, Integer.parseInt(times[1]));
set(SECOND, Integer.parseInt(times[2]));
}
/**
* 设置时间字段的值
* @param field 时间字段常量
* @param value 时间字段的值
*/
public void set(int field, int value) {
if(value < minFields[field]) {
throw new IllegalArgumentException(value +
", time value must be positive.");
}
fields[field] = value % (maxFields[field] + 1);
// 进行进位计算
int carry = value / (maxFields[field] + 1);
if(carry > 0) {
int upFieldValue = get(field + 1);
set(field + 1, upFieldValue + carry);
}
}
/**
* 获得时间字段的值
* @param field 时间字段常量
* @return 该时间字段的值
*/
public int get(int field) {
if(field < 0 || field > fields.length - 1) {
throw new IllegalArgumentException(field + ", field value is error.");
}
return fields[field];
}
/**
* 将时间进行“加”运算,即加上一个时间
* @param time 需要加的时间
* @return 运算后的时间
*/
public Time addTime(Time time) {
Time result = new Time();
int up = 0; // 进位标志
for (int i = 0; i < fields.length; i++) {
int sum = fields[i] + time.fields[i] + up;
up = sum / (maxFields[i] + 1);
result.fields[i] = sum % (maxFields[i] + 1);
}
return result;
}
/**
* 将时间进行“减”运算,即减去一个时间
* @param time 需要减的时间
* @return 运算后的时间
*/
public Time subtractTime(Time time) {
Time result = new Time();
int down = 0; // 退位标志
for (int i = 0, k = fields.length - 1; i < k; i++) {
int difference = fields[i] + down;
if (difference >= time.fields[i]) {
difference -= time.fields[i];
down = 0;
} else {
difference += maxFields[i] + 1 - time.fields[i];
down = -1;
}
result.fields[i] = difference;
}
result.fields[DAY] = fields[DAY] - time.fields[DAY] + down;
return result;
}
/**
* 获得时间字段的分隔符
* @return
*/
public String getTimeSeparator() {
return timeSeparator;
}
/**
* 设置时间字段的分隔符(用于字符串格式的时间)
* @param timeSeparator 分隔符字符串
*/
public void setTimeSeparator(String timeSeparator) {
this.timeSeparator = timeSeparator;
}
/**
* 正则表达式引用处理方法,源自 JDK @link java.util.regex.Pattern#quote(String)
*/
private String patternQuote(String s) {
int slashEIndex = s.indexOf("\\E");
if (slashEIndex == -1)
return "\\Q" + s + "\\E";
StringBuilder sb = new StringBuilder(s.length() * 2);
sb.append("\\Q");
slashEIndex = 0;
int current = 0;
while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
sb.append(s.substring(current, slashEIndex));
current = slashEIndex + 2;
sb.append("\\E\\\\E\\Q");
}
sb.append(s.substring(current, s.length()));
sb.append("\\E");
return sb.toString();
}
public String toString() {
DecimalFormat df = new DecimalFormat("00");
return new StringBuffer().append(fields[DAY]).append(", ")
.append(df.format(fields[HOUR])).append(timeSeparator)
.append(df.format(fields[MINUTE])).append(timeSeparator)
.append(df.format(fields[SECOND]))
.toString();
}
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + Arrays.hashCode(fields);
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Time other = (Time) obj;
if (!Arrays.equals(fields, other.fields)) {
return false;
}
return true;
}
}
常用的java函数(十)随机函数
/**
* @author talent_marquis<��˺��>
* Email: talent_marquis@163.com
* Copyright (C) 2007 talent_marquis<��˺��>
* All rights reserved.
*/
package com.dextrys.trilogy.util;
import java.util.Arrays;
import org.eclipse.swt.graphics.RGB;
public class RandomUtil
{
/**
* @param args
*/
public static void main( String[] args )
{
//System.out.println( getRandomNormalString( 8 ) );
int[] test = getRandomIntWithoutReduplicate( 0, 40, 39 );
Arrays.sort( test );
for( int i : test )
{
System.out.println( i );
}
}
/**
* get a integer array filled with random integer without reduplicate [min, max)
* @param min the minimum value
* @param max the maximum value
* @param size the capacity of the array
* @return a integer array filled with random integer without redupulicate
*/
public static int[] getRandomIntWithoutReduplicate( int min, int max, int size )
{
int[] result = new int[size];
int arraySize = max - min;
int[] intArray = new int[arraySize];
// init intArray
for( int i = 0 ; i < intArray.length ; i++ )
{
intArray[i] = i + min;
}
// get randome interger without reduplicate
for( int i = 0 ; i < size ; i++ )
{
int c = getRandomInt( min, max - i );
int index = c - min;
swap( intArray, index, arraySize - 1 - i );
result[i] = intArray[ arraySize - 1 - i ];
}
return result;
}
private static void swap( int[] array, int x, int y )
{
int temp = array[x];
array[x] = array[y];
array[y] = temp;
}
/**
* get a random Integer with the range [min, max)
* @param min the minimum value
* @param max the maximum value
* @return the random Integer value
*/
public static int getRandomInt( int min, int max )
{
// include min, exclude max
int result = min + new Double( Math.random() * ( max - min ) ).intValue();
return result;
}
/**
* get a random double with the range [min, max)
* @param min the minimum value
* @param max the maximum value
相关推荐
Java函数速查手册是编程学习过程中非常实用的参考资料,它主要涵盖了Java语言中常见的函数,对初学者来说尤其有价值。这个CHM文件很可能是由一系列的函数解释、示例代码和使用指南组成的电子手册,方便用户快速查找...
这里我们汇总了一些Java中常用的字符串相关函数,这些函数在处理文本数据时非常实用。 首先,`compareTo()`和`compareToIgnoreCase()`是用来比较两个字符串的函数。`compareTo()`根据ASCII值对字符串进行逐字符比较...
Java函数式编程是一种编程范式,它强调使用函数作为程序的基本构建块,将计算视为函数的组合,并且尽可能避免改变状态和可变数据。在Java 8及更高版本中,函数式编程得到了官方的大力支持,引入了Lambda表达式、...
在Java编程语言中,函数是实现特定功能的代码块,可以被多次调用。下面将分别介绍标题和描述中提到的一些重要函数,并结合压缩包内的文件名称,详细讲解相关类和方法。 1. **BSDate.java**: 这个文件很可能包含了...
以下是一些重要的Java函数及其应用场景: 1. **String类**:String类提供了大量的操作字符串的方法,如`substring()`用于截取字符串,`concat()`用于连接字符串,`indexOf()`和`lastIndexOf()`用于查找子串位置,`...
Java函数式编程是一种将函数作为一等公民的编程范式,它强调使用函数来构造程序,减少副作用,提高代码的可读性和可维护性。在Java 8及更高版本中,函数式编程得到了显著增强,引入了Lambda表达式、函数接口、Stream...
在Java编程中,掌握常用函数是提升开发效率的关键。本篇将深入讲解Java中涉及字符串、包装类、日期处理、基础数学操作以及其他实用工具类的相关函数,以及GUI组件如文本框、文本区、按钮和标签的使用。 首先,我们...
Java常用函数2 本文档介绍了Java中的一些常用的函数,包括日期格式转换、判断素数、阶乘计算、十六进制打印和数据库连接等。 1. 日期格式转换函数 dateToStr函数将java.util.Date对象转换为字符串,使用...
这份“JAVA函数使用手册”可能是针对Java编程中的函数使用方法、设计原则以及常见问题的详细指南。以下是关于Java函数的一些关键知识点: 1. **函数定义与调用**:在Java中,函数通过`public void functionName参数...
java函数java函数java函数
本案例探讨的是如何使用C++调用Java函数,这通常涉及到JNI(Java Native Interface)技术。以下是对这个实战项目的详细解释: 首先,我们要理解标题"实战-C++调用Java函数"所涉及的核心知识点。C++是一种强大的系统...
Java函数查询是一个非常实用的工具,它为Java开发者提供了一个快速查找和理解Java类库中各种函数的方法。这个工具能够极大地提升开发效率,减少在编程过程中查找相关API的时间。下面我们将详细探讨Java函数查询的...
Java函数中文速查手册是一本极其实用的工具书,旨在帮助Java学习者快速查询和理解各种函数的使用方法,从而提升编程效率和实践能力。在Java这个强大的面向对象编程语言中,函数是实现功能的基本单元,掌握好函数的...
Java函数速查是Java开发者日常工作中不可或缺的参考资料。它涵盖了Java语言中各种核心类库、API及常用函数的使用方法,旨在帮助开发者快速查找和理解函数的用途、参数及返回值,提高编程效率。以下是对Java函数的...
Java函数速查是一个非常实用的资源,对于程序员来说,它是一个高效的工具,帮助开发者快速查找和理解Java语言中的各种函数用法。这个压缩包可能包含了详细的函数文档、示例代码和可能的分类索引,方便用户按需查找。...
Java 8函数式编程
Java函数速查中文版是Java开发者的重要参考资料,它包含了丰富的Java API函数的详细信息,帮助开发者快速查找并理解各种函数的用法。这份资源对于学习和提升Java编程技能非常有帮助,尤其对于初学者和在项目开发中...
Java函数式编程是一种高效、简洁的编程范式,它在Java 8中得到了全面支持,大大改变了Java开发人员编写代码的方式。本套黑马程序员的Java函数式编程视频教程涵盖了Lambda表达式、Stream流以及函数式编程的核心概念,...
本篇文章将深入探讨Java中一些常用的函数API,尤其是那些在日常开发中频繁使用的。 首先,我们要关注的是`java.util.Date`和`java.text.SimpleDateFormat`类,这两个类常用于日期和时间的操作。`Date`类代表了一个...
### Java函数介绍与详解 #### 一、函数概述 在计算机编程领域,函数扮演着至关重要的角色,被视为程序设计中最基础且关键的组成部分之一。它不仅简化了代码结构,提高了代码的可重用性,还使得程序逻辑更加清晰。...