1 /**
2 * 将某个日期以固定格式转化成字符串
3 *
4 * @param date
5 * @return String
6 */
7 public static String dateToStr(java.util.Date date)
8 {
9 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
10 String str = sdf.format(date);
11 return str;
12 }
13
14
15
16 /**
17 * 判断任意一个整数是否素数
18 *
19 * @param n
20 * @return boolean
21 */
22 public static boolean isPrimes(int n)
23 {
24 for (int i = 2; i <= Math.sqrt(n); i++)
25 {
26 if (n % i == 0)
27 {
28 return false;
29 }
30 }
31 return true;
32 }
33
34
35 /**
36 * 获得任意一个整数的阶乘,递归
37 *
38 * @param n
39 * @return n!
40 */
41 public static int factorial(int n)
42 {
43 if (n == 1)
44 {
45 return 1;
46 }
47 return n * factorial(n - 1);
48 }
49
50 /**
51 * 将指定byte数组以16进制的形式打印到控制台
52 *
53 * @param hint
54 * String
55 * @param b
56 * byte[]
57 * @return void
58 */
59 public static void printHexString(String hint, byte[] b)
60 {
61 System.out.print(hint);
62 for (int i = 0; i < b.length; i++)
63 {
64 String hex = Integer.toHexString(b & 0xFF);
65 if (hex.length() == 1)
66 {
67 hex = '0' + hex;
68 }
69 System.out.print(hex.toUpperCase() + " ");
70 }
71 System.out.println("");
72 }
73
74
75 package net.java2000.tools;
76
77 /**
78 * Title: Java Bean 工具
79 * @version 1.0
80 */
81 import java.util.*;
82 import java.util.regex.Pattern;
83
84 public class StrTools {
85 /**
86 * 分割字符串
87 *
88 * @param str String 原始字符串
89 * @param splitsign String 分隔符
90 * @return String[] 分割后的字符串数组
91 */
92 @SuppressWarnings("unchecked")
93 public static String[] split(String str, String splitsign) {
94 int index;
95 if (str == null || splitsign == null)
96 return null;
97 ArrayList al = new ArrayList();
98 while ((index = str.indexOf(splitsign)) != -1) {
99 al.add(str.substring(0, index));
100 str = str.substring(index + splitsign.length());
101 }
102 al.add(str);
103 return (String[]) al.toArray(new String[0]);
104 }
105
106 /**
107 * 替换字符串
108 *
109 * @param from String 原始字符串
110 * @param to String 目标字符串
111 * @param source String 母字符串
112 * @return String 替换后的字符串
113 */
114 public static String replace(String from, String to, String source) {
115 if (source == null || from == null || to == null)
116 return null;
117 StringBuffer bf = new StringBuffer("");
118 int index = -1;
119 while ((index = source.indexOf(from)) != -1) {
120 bf.append(source.substring(0, index) + to);
121 source = source.substring(index + from.length());
122 index = source.indexOf(from);
123 }
124 bf.append(source);
125 return bf.toString();
126 }
127
128 /**
129 * 替换字符串,能能够在HTML页面上直接显示(替换双引号和小于号)
130 *
131 * @param str String 原始字符串
132 * @return String 替换后的字符串
133 */
134 public static String htmlencode(String str) {
135 if (str == null) {
136 return null;
137 }
138
139 return replace("\"", """, replace("<", "<", str));
140 }
141
142 /**
143 * 替换字符串,将被编码的转换成原始码(替换成双引号和小于号)
144 *
145 * @param str String
146 * @return String
147 */
148 public static String htmldecode(String str) {
149 if (str == null) {
150 return null;
151 }
152
153 return replace(""", "\"", replace("<", "<", str));
154 }
155
156 private static final String _BR = "<br/>";
157
158 /**
159 * 在页面上直接显示文本内容,替换小于号,空格,回车,TAB
160 *
161 * @param str String 原始字符串
162 * @return String 替换后的字符串
163 */
164 public static String htmlshow(String str) {
165 if (str == null) {
166 return null;
167 }
168
169 str = replace("<", "<", str);
170 str = replace(" ", " ", str);
171 str = replace("\r\n", _BR, str);
172 str = replace("\n", _BR, str);
173 str = replace("\t", " ", str);
174 return str;
175 }
176
177 /**
178 * 返回指定字节长度的字符串
179 *
180 * @param str String 字符串
181 * @param length int 指定长度
182 * @return String 返回的字符串
183 */
184 public static String toLength(String str, int length) {
185 if (str == null) {
186 return null;
187 }
188 if (length <= 0) {
189 return "";
190 }
191 try {
192 if (str.getBytes("GBK").length <= length) {
193 return str;
194 }
195 } catch (Exception ex) {
196 }
197 StringBuffer buff = new StringBuffer();
198
199 int index = 0;
200 char c;
201 length -= 3;
202 while (length > 0) {
203 c = str.charAt(index);
204 if (c < 128) {
205 length--;
206 } else {
207 length--;
208 length--;
209 }
210 buff.append(c);
211 index++;
212 }
213 buff.append("...");
214 return buff.toString();
215 }
216
217 /**
218 * 判断是否为整数
219 *
220 * @param str 传入的字符串
221 * @return 是整数返回true,否则返回false
222 */
223 public static boolean isInteger(String str) {
224 Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
225 return pattern.matcher(str).matches();
226 }
227
228 /**
229 * 判断是否为浮点数,包括double和float
230 *
231 * @param str 传入的字符串
232 * @return 是浮点数返回true,否则返回false
233 */
234 public static boolean isDouble(String str) {
235 Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
236 return pattern.matcher(str).matches();
237 }
238
239 /**
240 * 判断输入的字符串是否符合Email样式.
241 *
242 * @param str 传入的字符串
243 * @return 是Email样式返回true,否则返回false
244 */
245 public static boolean isEmail(String str) {
246 Pattern pattern = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
247 return pattern.matcher(str).matches();
248 }
249
250 /**
251 * 判断输入的字符串是否为纯汉字
252 *
253 * @param str 传入的字符窜
254 * @return 如果是纯汉字返回true,否则返回false
255 */
256 public static boolean isChinese(String str) {
257 Pattern pattern = Pattern.compile("[\u0391-\uFFE5]+$");
258 return pattern.matcher(str).matches();
259 }
260
261 /**
262 * 是否为空白,包括null和""
263 *
264 * @param str
265 * @return
266 */
267 public static boolean isBlank(String str) {
268 return str == null || str.trim().length() == 0;
269 }
270
271 /**
272 * 判断是否为质数
273 *
274 * @param x
275 * @return
276 */
277 public static boolean isPrime(int x) {
278 if (x <= 7) {
279 if (x == 2 || x == 3 || x == 5 || x == 7)
280 return true;
281 }
282 int c = 7;
283 if (x % 2 == 0)
284 return false;
285 if (x % 3 == 0)
286 return false;
287 if (x % 5 == 0)
288 return false;
289 int end = (int) Math.sqrt(x);
290 while (c <= end) {
291 if (x % c == 0) {
292 return false;
293 }
294 c += 4;
295 if (x % c == 0) {
296 return false;
297 }
298 c += 2;
299 if (x % c == 0) {
300 return false;
301 }
302 c += 4;
303 if (x % c == 0) {
304 return false;
305 }
306 c += 2;
307 if (x % c == 0) {
308 return false;
309 }
310 c += 4;
311 if (x % c == 0) {
312 return false;
313 }
314 c += 6;
315 if (x % c == 0) {
316 return false;
317 }
318 c += 2;
319 if (x % c == 0) {
320 return false;
321 }
322 c += 6;
323 }
324 return true;
325 }
326
327 public static void main(String[] args) {
328 String[] numbers = { "12345", "-12345", "123.45", "-123.45", ".12345", "-.12345", "a12345", "12345a", "123.a45" };
329 for (String str : numbers) {
330 System.out.println(str + "=" + isInteger(str) + " " + isDouble(str));
331 }
332
333 String[] emails = { "1@2.com", "1.2@3.com", "1@3.4.5.com" };
334 for (String str : emails) {
335 System.out.println(str + "=" + isEmail(str));
336 }
337 String[] chineses = { "中国", "1中国", "中国1", "1中国2", "中1国" };
338 for (String str : chineses) {
339 System.out.println(str + "=" + isChinese(str));
340 }
341 }
342 }
343
344
345
346
347 /* * Db.java
348 Created on 2007年8月20日, 上午 8:37
349 */
350 import java.io.*;
351 import java.sql.*;
352 import java.util.Properties;
353 public class Db {
354 private String driver;
355 private String url;
356 private String user;
357 private String password;
358 private Connection conn;
359 private Statement stm;
360 private ResultSet rs;
361 public Db(){
362 this("DBConf.properties");
363 }
364 public Db(String conf) {
365 loadProperties(conf);
366 setConn();
367 }
368 public Connection getConn(){
369 return this.conn;
370 }
371 //handle the properties file to get the informations for connection
372 private void loadProperties(String conf){
373 Properties props = new Properties();
374 try {
375 props.load(new FileInputStream(conf));
376 } catch (FileNotFoundException e) {
377 e.printStackTrace();
378 } catch (IOException e) {
379 e.printStackTrace();
380 }
381 this.driver = props.getProperty("driver");
382 this.url = props.getProperty("url");
383 this.user = props.getProperty("user");
384 this.password = props.getProperty("password");
385 }
386 //implement the Connection
387 private void setConn(){
388 try {
389 Class.forName(driver);
390 this.conn = DriverManager.getConnection(url,user,password);
391 } catch(ClassNotFoundException classnotfoundexception) {
392 classnotfoundexception.printStackTrace();
393 System.err.println("db: " + classnotfoundexception.getMessage());
394 } catch(SQLException sqlexception) {
395 System.err.println("db.getconn(): " + sqlexception.getMessage());
396 }
397 }
398 public void doInsert(String sql) {
399 try {
400 Statement statement = conn.createStatement();
401 int i = stm.executeUpdate(sql);
402 } catch(SQLException sqlexception) {
403 System.err.println("db.executeInset:" + sqlexception.getMessage());
404 }
405 }
406 public void doDelete(String sql) {
407 try {
408 stm = conn.createStatement();
409 int i = stm.executeUpdate(sql);
410 } catch(SQLException sqlexception) {
411 System.err.println("db.executeDelete:" + sqlexception.getMessage());
412 }
413 }
414 public void doUpdate(String sql) {
415 try {
416 stm = conn.createStatement();
417 int i = stm.executeUpdate(sql);
418 } catch(SQLException sqlexception) {
419 System.err.println("db.executeUpdate:" + sqlexception.getMessage());
420 }
421 }
422
423 public ResultSet doSelect(String sql) {
424 try {
425 stm = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY);
426 rs = stm.executeQuery(sql);
427 } catch(SQLException sqlexception) {
428 System.err.println("db.executeQuery: " + sqlexception.getMessage());
429 }
430 return rs;
431 }
432 public static void main(String[] args){
433 try{
434 Db db = new Db();
435 Connection conn = db.getConn();
436 if(conn != null && !conn.isClosed()) {
437 System.out.println("連結成功");
438 ResultSet rs = db.doSelect("select * from content");
439 while(rs.next()){
440 System.out.println(rs.getString(1)+":"+rs.getString(2)+":"+rs.getString(3));
441 }
442 rs.close();
443 conn.close();
444 }
445 }catch(SQLException e) {
446 e.printStackTrace();
447 }
448 }
449 }
450
451
452
453
454
455 DBConf.properties:
456 driver=oracle.jdbc.driver.OracleDriver
457 url=jdbcracle:thintdt151:1521:train
458 user=XX
459 password=XX
460
461
462
463 /**
464 * 人民币转成大写
465 *
466 * @param value
467 * @return String
468 */
469 public static String hangeToBig(double value)
470 {
471 char[] hunit = { '拾', '佰', '仟' }; // 段内位置表示
472 char[] vunit = { '万', '亿' }; // 段名表示
473 char[] digit = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' }; // 数字表示
474 long midVal = (long) (value * 100); // 转化成整形
475 String valStr = String.valueOf(midVal); // 转化成字符串
476
477 String head = valStr.substring(0, valStr.length() - 2); // 取整数部分
478 String rail = valStr.substring(valStr.length() - 2); // 取小数部分
479
480 String prefix = ""; // 整数部分转化的结果
481 String suffix = ""; // 小数部分转化的结果
482 // 处理小数点后面的数
483 if (rail.equals("00"))
484 { // 如果小数部分为0
485 suffix = "整";
486 }
487 else
488 {
489 suffix = digit[rail.charAt(0) - '0'] + "角" + digit[rail.charAt(1) - '0'] + "分"; // 否则把角分转化出来
490 }
491 // 处理小数点前面的数
492 char[] chDig = head.toCharArray(); // 把整数部分转化成字符数组
493 char zero = '0'; // 标志'0'表示出现过0
494 byte zeroSerNum = 0; // 连续出现0的次数
495 for (int i = 0; i < chDig.length; i++)
496 { // 循环处理每个数字
497 int idx = (chDig.length - i - 1) % 4; // 取段内位置
498 int vidx = (chDig.length - i - 1) / 4; // 取段位置
499 if (chDig == '0')
500 { // 如果当前字符是0
501 zeroSerNum++; // 连续0次数递增
502 if (zero == '0')
503 { // 标志
504 zero = digit[0];
505 }
506 else if (idx == 0 && vidx > 0 && zeroSerNum < 4)
507 {
508 prefix += vunit[vidx - 1];
509 zero = '0';
510 }
511 continue;
512 }
513 zeroSerNum = 0; // 连续0次数清零
514 if (zero != '0')
515 { // 如果标志不为0,则加上,例如万,亿什么的
516 prefix += zero;
517 zero = '0';
518 }
519 prefix += digit[chDig - '0']; // 转化该数字表示
520 if (idx > 0)
521 prefix += hunit[idx - 1];
522 if (idx == 0 && vidx > 0)
523 {
524 prefix += vunit[vidx - 1]; // 段结束位置应该加上段名如万,亿
525 }
526 }
527
528 if (prefix.length() > 0)
529 prefix += '圆'; // 如果整数部分存在,则有圆的字样
530 return prefix + suffix; // 返回正确表示
531 }
532
533
534 /**
535 * 全角字符转半角字符
536 *
537 * @param QJStr
538 * @return String
539 */
540 public static final String QJToBJChange(String QJStr)
541 {
542 char[] chr = QJStr.toCharArray();
543 String str = "";
544 for (int i = 0; i < chr.length; i++)
545 {
546 chr = (char) ((int) chr - 65248);
547 str += chr;
548 }
549 return str;
550 }
551
552
553 /**
554 * 去掉字符串中重复的子字符串
555 *
556 * @param str
557 * @return String
558 */
559 private static String removeSameString(String str)
560 {
561 Set<String> mLinkedSet = new LinkedHashSet<String>();
562 String[] strArray = str.split(" ");
563 StringBuffer sb = new StringBuffer();
564
565 for (int i = 0; i < strArray.length; i++)
566 {
567 if (!mLinkedSet.contains(strArray))
568 {
569 mLinkedSet.add(strArray);
570 sb.append(strArray + " ");
571 }
572 }
573 System.out.println(mLinkedSet);
574 return sb.toString().substring(0, sb.toString().length() - 1);
575 }
576
577
578
579
580 /**
581 * 设置JSpinner的编辑属性
582 * @param spinner 目标JSpinner
583 * @param isAllowInvalid 是否允许输入非法值
584 * @param isEditable 是否允许编辑
585 */
586 public static void setAllowsInvalid(JSpinner spinner, boolean isAllowInvalid, boolean isEditable)
587 {
588 JSpinner.NumberEditor editor = new JSpinner.NumberEditor(spinner, "#");
589 spinner.setEditor(editor);
590 JFormattedTextField tf = ((JSpinner.NumberEditor)spinner.getEditor()).getTextField();
591 tf.setEditable(isEditable);
592 DefaultFormatterFactory factory = (DefaultFormatterFactory)tf.getFormatterFactory();
593 NumberFormatter formatter = (NumberFormatter)factory.getDefaultFormatter();
594 formatter.setAllowsInvalid(isAllowInvalid);
595 }
596
597
598
599
600 /**
601 * 根据指定方法的参数去构造一个新的对象的拷贝并将他返回
602 * @param obj 原始对象
603 * @return 新对象
604 * @throws NoSuchMethodException
605 * @throws InvocationTargetException
606 * @throws IllegalAccessException
607 * @throws InstantiationException
608 * @throws SecurityException
609 * @throws IllegalArgumentException
610 */
611 @SuppressWarnings("unchecked")
612 public static Object copy(Object obj) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException,
613 InvocationTargetException, NoSuchMethodException
614 {
615 //获得对象的类型
616 Class classType = obj.getClass();
617
618 //通过默认构造方法去创建一个新的对象,getConstructor的视其参数决定调用哪个构造方法
619 Object objectCopy = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});
620
621 //获得对象的所有属性
622 Field[] fields = classType.getDeclaredFields();
623
624 for(int i = 0; i < fields.length; i++)
625 {
626 //获取数组中对应的属性
627 Field field = fields;
628
629 String fieldName = field.getName();
630 String stringLetter = fieldName.substring(0, 1).toUpperCase();
631
632 //获得相应属性的getXXX和setXXX方法名称
633 String getName = "get" + stringLetter + fieldName.substring(1);
634 String setName = "set" + stringLetter + fieldName.substring(1);
635
636 //获取相应的方法
637 Method getMethod = classType.getMethod(getName, new Class[]{});
638 Method setMethod = classType.getMethod(setName, new Class[]{field.getType()});
639
640 //调用源对象的getXXX()方法
641 Object value = getMethod.invoke(obj, new Object[]{});
642
643 //调用拷贝对象的setXXX()方法
644 setMethod.invoke(objectCopy, new Object[]{value});
645 }
646
647 return objectCopy;
648 }
649
650
651 //过滤特殊字符
652 public static String encoding(String src){
653 if (src==null)
654 return "";
655 StringBuilder result=new StringBuilder();
656 if (src!=null){
657 src=src.trim();
658 for (int pos=0;pos<src.length();pos++){
659 switch(src.charAt(pos)){
660 case '\"':result.append(""");break;
661 case '<':result.append("<");break;
662 case '>':result.append(">");break;
663 case '\'':result.append("'");break;
664 case '&':result.append("&");break;
665 case '%':result.append("&pc;");break;
666 case '_':result.append("&ul;");break;
667 case '#':result.append("&shap;");break;
668 case '?':result.append("&ques;");break;
669 default:result.append(src.charAt(pos));break;
670 }
671 }
672 }
673 return result.toString();
674 }
675
676 //反过滤特殊字符
677 public static String decoding(String src){
678 if (src==null)
679 return "";
680 String result=src;
681 result=result.replace(""", "\"").replace("'", "\'");
682 result=result.replace("<", "<").replace(">", ">");
683 result=result.replace("&", "&");
684 result=result.replace("&pc;", "%").replace("&ul", "_");
685 result=result.replace("&shap;", "#").replace("&ques", "?");
686 return result;
687 }
688
689 //利用反射调用一个继承层次上的函数族,比如安装程序,有安装数据库的,安装文件系统的等,命名均已“install”开始,你就可以将参数part设为“install”,src是其实类实例,root是终止父类
690 public static <T> void invokeMethods(String part,T src,Class root) throws ExceptionManager{
691 if (root!=null){
692 if (!root.isInstance(src))return;
693 root=(Class)root.getGenericSuperclass();
694 }
695 HashMap<String,Method> invokees=new HashMap<String,Method>();
696 Class target=src.getClass();
697 do{
698 Method [] methods=target.getDeclaredMethods();
699 for (Method method:methods){
700 String mn=method.getName();
701 Boolean isPass=mn.startsWith(part);
702 if (isPass){
703 Integer nopt=method.getParameterTypes().length;
704 Boolean isStatic=Modifier.isStatic(method.getModifiers());
705 if ((nopt==0)&&(!isStatic)){
706 if (!invokees.containsKey(mn))
707 invokees.put(mn, method);
708 }
709 }
710 }
711 target=(Class)target.getGenericSuperclass();
712 }while(target!=root);
713 Iterator<String> methods=invokees.keySet().iterator();
714 while (methods.hasNext()){
715 Method invokee=invokees.get(methods.next());
716 Boolean access=invokee.isAccessible();
717 invokee.setAccessible(true);
718 try {
719 invokee.invoke(src);
720 } catch (InvocationTargetException e) {
721 throw ExceptionManager.wrap(e.getTargetException());
722 }catch (Exception e){}
723 invokee.setAccessible(access);
724 }
725 }
726
727
728
729 MySQL:
730 String Driver="com.mysql.jdbc.Driver"; //驱动程序
731 String URL="jdbc:mysql://localhost:3306/db_name"; //连接的URL,db_name为数据库名
732 String Username="username"; //用户名
733 String Password="password"; //密码
734 Class.forName(Driver).new Instance();
735 Connection con=DriverManager.getConnection(URL,Username,Password);
736 Microsoft SQL Server 2.0驱动(3个jar的那个):
737 String Driver="com.microsoft.jdbc.sqlserver.SQLServerDriver"; //连接SQL数据库的方法
738 String URL="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_name"; //db_name为数据库名
739 String Username="username"; //用户名
740 String Password="password"; //密码
741 Class.forName(Driver).new Instance(); //加载数据可驱动
742 Connection con=DriverManager.getConnection(URL,UserName,Password); //
743 Microsoft SQL Server 3.0驱动(1个jar的那个): // 老紫竹完善
744 String Driver="com.microsoft.sqlserver.jdbc.SQLServerDriver"; //连接SQL数据库的方法
745 String URL="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_name"; //db_name为数据库名
746 String Username="username"; //用户名
747 String Password="password"; //密码
748 Class.forName(Driver).new Instance(); //加载数据可驱动
749 Connection con=DriverManager.getConnection(URL,UserName,Password); //
750 Sysbase:
751 String Driver="com.sybase.jdbc.SybDriver"; //驱动程序
752 String URL="jdbc:Sysbase://localhost:5007/db_name"; //db_name为数据可名
753 String Username="username"; //用户名
754 String Password="password"; //密码
755 Class.forName(Driver).newInstance();
756 Connection con=DriverManager.getConnection(URL,Username,Password);
757 Oracle(用thin模式):
758 String Driver="oracle.jdbc.driver.OracleDriver"; //连接数据库的方法
759 String URL="jdbcracle:thinloaclhost:1521rcl"; //orcl为数据库的SID
760 String Username="username"; //用户名
761 String Password="password"; //密码
762 Class.forName(Driver).newInstance(); //加载数据库驱动
763 Connection con=DriverManager.getConnection(URL,Username,Password);
764 PostgreSQL:
765 String Driver="org.postgresql.Driver"; //连接数据库的方法
766 String URL="jdbc:postgresql://localhost/db_name"; //db_name为数据可名
767 String Username="username"; //用户名
768 String Password="password"; //密码
769 Class.forName(Driver).newInstance();
770 Connection con=DriverManager.getConnection(URL,Username,Password);
771 DB2:
772 String Driver="com.ibm.db2.jdbc.app.DB2.Driver"; //连接具有DB2客户端的Provider实例
773 //String Driver="com.ibm.db2.jdbc.net.DB2.Driver"; //连接不具有DB2客户端的Provider实例
774 String URL="jdbc:db2://localhost:5000/db_name"; //db_name为数据可名
775 String Username="username"; //用户名
776 String Password="password"; //密码
777 Class.forName(Driver).newInstance();
778 Connection con=DriverManager.getConnection(URL,Username,Password);
779 Informix:
780 String Driver="com.informix.jdbc.IfxDriver";
781 String URL="jdbc:Informix-sqli://localhost:1533/db_name:INFORMIXSER=myserver"; //db_name为数据可名
782 String Username="username"; //用户名
783 String Password="password"; //密码
784 Class.forName(Driver).newInstance();
785 Connection con=DriverManager.getConnection(URL,Username,Password);
786 JDBC-ODBC:
787 String Driver="sun.jdbc.odbc.JdbcOdbcDriver";
788 String URL="jdbcdbc:dbsource"; //dbsource为数据源名
789 String Username="username"; //用户名
790 String Password="password"; //密码
791 Class.forName(Driver).newInstance();
792 Connection con=DriverManager.getConnection(URL,Username,Password);
793
794
795
796
797
798
799 /**
800 * 把TXT转换为XML
801 */
802 import java.io.BufferedReader;
803 import java.io.BufferedWriter;
804 import java.io.FileReader;
805 import java.io.FileWriter;
806 import java.util.StringTokenizer;
807
808 public class TxtToXml {
809 private String strTxtFileName;
810
811 private String strXmlFileName;
812
813 public TxtToXml() {
814 strTxtFileName = new String();
815 strXmlFileName = new String();
816 }
817
818 public void createXml(String strTxt, String strXml) {
819 strTxtFileName = strTxt;
820 strXmlFileName = strXml;
821 String strTmp;
822 try {
823 BufferedReader inTxt = new BufferedReader(new FileReader(
824 strTxtFileName));
825 BufferedWriter outXml = new BufferedWriter(new FileWriter(
826 strXmlFileName));
827 outXml.write("<?xml version= \"1.0\" encoding=\"gb2312\"?>");
828 outXml.newLine();
829 outXml.write("<people>");
830 while ((strTmp = inTxt.readLine()) != null) {
831 StringTokenizer strToken = new StringTokenizer(strTmp, ",");
832 String arrTmp[];
833 arrTmp = new String[3];
834 for (int i = 0; i < 3; i++)
835 arrTmp = new String("");
836 int index = 0;
837 outXml.newLine();
838 outXml.write(" <students>");
839 while (strToken.hasMoreElements()) {
840 strTmp = (String) strToken.nextElement();
841 strTmp = strTmp.trim();
842 arrTmp[index++] = strTmp;
843 }
844 outXml.newLine();
845 outXml.write(" <name>" + arrTmp[0] + "</name>");
846 outXml.newLine();
847 outXml.write(" <sex>" + arrTmp[1] + "</sex>");
848 outXml.newLine();
849 outXml.write(" <age>" + arrTmp[2] + "</age>");
850 outXml.newLine();
851 outXml.write(" </students>");
852 }
853 outXml.newLine();
854 outXml.write("</people>");
855 outXml.flush();
856 } catch (Exception e) {
857 e.printStackTrace();
858 }
859 }
860
861 public static void main(String[] args) {
862 String txtName = "testtxt.txt";
863 String xmlName = "testxml.xml";
864 TxtToXml thisClass = new TxtToXml();
865 thisClass.createXml(txtName, xmlName);
866 }
867 }
868
869
870 /**
871 * 写入日志
872 * filePath 日志文件的路径
873 * code 要写入日志文件的内容
874 */
875 public static boolean print(String filePath,String code) {
876 try {
877 File tofile=new File(filePath);
878 FileWriter fw=new FileWriter(tofile,true);
879 BufferedWriter bw=new BufferedWriter(fw);
880 PrintWriter pw=new PrintWriter(bw);
881
882 System.out.println(getDate()+":"+code);
883 pw.println(getDate()+":"+code);
884 pw.close();
885 bw.close();
886 fw.close();
887 return true;
888 } catch (IOException e) {
889 return false;
890 }
891 }
892
893
894
895 /**
896 * 判断是不是合法手机
897 * handset 手机号码
898 */
899 public static boolean isHandset(String handset) {
900 try {
901 if(!handset.substring(0,1).equals("1")) {
902 return false;
903 }
904 if (handset==null || handset.length()!=11) {
905 return false;
906 }
907 String check = "^[0123456789]+$";
908 Pattern regex = Pattern.compile(check);
909 Matcher matcher = regex.matcher(handset);
910 boolean isMatched = matcher.matches();
911 if(isMatched) {
912 return true;
913 } else {
914 return false;
915 }
916 } catch (RuntimeException e) {
917 return false;
918 }
919 }
920 }
921
922 字符串匹配的算法.
923 public String getMaxMatch(String a,String b) {
924 StringBuffer tmp = new StringBuffer();
925 String maxString = "";
926 int max = 0;
927 int len = 0;
928 char[] aArray = a.toCharArray();
929 char[] bArray = b.toCharArray();
930 int posA = 0;
931 int posB = 0;
932 while(posA<aArray.length-max) {
933 posB = 0;
934 while(posB<(bArray.length-max)) {
935 if(aArray[posA]==bArray[posB]) {
936 len = 1;
937 tmp = new StringBuffer();
938 tmp.append(aArray[posA]);
939 while((posA+len<aArray.length)&&(posB+len<bArray.length)&&(aArray[posA+len]==bArray[posB+len])) {
940 tmp.append(aArray[posA+len]);
941 len++;
942 }
943 if(len>max) {
944 max = len;
945 maxString = tmp.toString();
946 }
947 }
948 posB++;
949 }
950 posA++;
951 }
952 return maxString;
953 }
954
955
956
957 import java.text.DecimalFormat;
958 import java.util.Arrays;
959
960 /**
961 * 时间计算工具类
962 */
963 public class Time {
964
965 /**
966 * 时间字段常量,表示“秒”
967 */
968 public final static int SECOND = 0;
969
970 /**
971 * 时间字段常量,表示“分”
972 */
973 public final static int MINUTE = 1;
974
975 /**
976 * 时间字段常量,表示“时”
977 */
978 public final static int HOUR = 2;
979
980 /**
981 * 时间字段常量,表示“天”
982 */
983 public final static int DAY = 3;
984
985 /**
986 * 各常量允许的最大值
987 */
988 private final int[] maxFields = { 59, 59, 23, Integer.MAX_VALUE - 1 };
989
990 /**
991 * 各常量允许的最小值
992 */
993 private final int[] minFields = { 0, 0, 0, Integer.MIN_VALUE };
994
995 /**
996 * 默认的字符串格式时间分隔符
997 */
998 private String timeSeparator = ":";
999
1000 /**
1001 * 时间数据容器
1002 */
1003 private int[] fields = new int[4];
1004
1005 /**
1006 * 无参构造,将各字段置为 0
1007 */
1008 public Time() {
1009 this(0, 0, 0, 0);
1010 }
1011
1012 /**
1013 * 使用时、分构造一个时间
1014 * @param hour 小时
1015 * @param minute 分钟
1016 */
1017 public Time(int hour, int minute) {
1018 this(0, hour, minute, 0);
1019 }
1020
1021 /**
1022 * 使用时、分、秒构造一个时间
1023 * @param hour 小时
1024 * @param minute 分钟
1025 * @param second 秒
1026 */
1027 public Time(int hour, int minute, int second) {
1028 this(0, hour, minute, second);
1029 }
1030
1031 /**
1032 * 使用一个字符串构造时间<br/>
1033 * Time time = new Time("14:22:23");
1034 * @param time 字符串格式的时间,默认采用“:”作为分隔符
1035 */
1036 public Time(String time) {
1037 this(time, null);
1038 }
1039
1040 /**
1041 * 使用天、时、分、秒构造时间,进行全字符的构造
1042 * @param day 天
1043 * @param hour 时
1044 * @param minute 分
1045 * @param second 秒
1046 */
1047 public Time(int day, int hour, int minute, int second) {
1048 set(DAY, day);
1049 set(HOUR, hour);
1050 set(MINUTE, minute);
1051 set(SECOND, second);
1052 }
1053
1054 /**
1055 * 使用一个字符串构造时间,指定分隔符<br/>
1056 * Time time = new Time("14-22-23", "-");
1057 * @param time 字符串格式的时间
1058 */
1059 public Time(String time, String timeSeparator) {
1060 if(timeSeparator != null) {
1061 setTimeSeparator(timeSeparator);
1062 }
1063 String pattern = patternQuote(this.timeSeparator);
1064 String matcher = new StringBuffer()
1065 .append("\\d+?").append(pattern)
1066 .append("\\d+?").append(pattern)
1067 .append("\\d+?")
1068 .toString();
1069 if(!time.matches(matcher)) {
1070 throw new IllegalArgumentException(time + ", time format error, HH"
1071 + this.timeSeparator + "mm" + this.timeSeparator + "ss");
1072 }
1073 String[] times = time.split(pattern);
1074 set(DAY, 0);
1075 set(HOUR, Integer.parseInt(times[0]));
1076 set(MINUTE, Integer.parseInt(times[1]));
1077 set(SECOND, Integer.parseInt(times[2]));
1078 }
1079
1080 /**
1081 * 设置时间字段的值
1082 * @param field 时间字段常量
1083 * @param value 时间字段的值
1084 */
1085 public void set(int field, int value) {
1086 if(value < minFields[field]) {
1087 throw new IllegalArgumentException(value +
1088 ", time value must be positive.");
1089 }
1090 fields[field] = value % (maxFields[field] + 1);
1091 // 进行进位计算
1092 int carry = value / (maxFields[field] + 1);
1093 if(carry > 0) {
1094 int upFieldValue = get(field + 1);
1095 set(field + 1, upFieldValue + carry);
1096 }
1097 }
1098
1099 /**
1100 * 获得时间字段的值
1101 * @param field 时间字段常量
1102 * @return 该时间字段的值
1103 */
1104 public int get(int field) {
1105 if(field < 0 || field > fields.length - 1) {
1106 throw new IllegalArgumentException(field + ", field value is error.");
1107 }
1108 return fields[field];
1109 }
1110
1111 /**
1112 * 将时间进行“加”运算,即加上一个时间
1113 * @param time 需要加的时间
1114 * @return 运算后的时间
1115 */
1116 public Time addTime(Time time) {
1117 Time result = new Time();
1118 int up = 0; // 进位标志
1119 for (int i = 0; i < fields.length; i++) {
1120 int sum = fields + time.fields + up;
1121 up = sum / (maxFields + 1);
1122 result.fields = sum % (maxFields + 1);
1123 }
1124 return result;
1125 }
1126
1127 /**
1128 * 将时间进行“减”运算,即减去一个时间
1129 * @param time 需要减的时间
1130 * @return 运算后的时间
1131 */
1132 public Time subtractTime(Time time) {
1133 Time result = new Time();
1134 int down = 0; // 退位标志
1135 for (int i = 0, k = fields.length - 1; i < k; i++) {
1136 int difference = fields + down;
1137 if (difference >= time.fields) {
1138 difference -= time.fields;
1139 down = 0;
1140 } else {
1141 difference += maxFields + 1 - time.fields;
1142 down = -1;
1143 }
1144 result.fields = difference;
1145 }
1146 result.fields[DAY] = fields[DAY] - time.fields[DAY] + down;
1147 return result;
1148 }
1149
1150 /**
1151 * 获得时间字段的分隔符
1152 * @return
1153 */
1154 public String getTimeSeparator() {
1155 return timeSeparator;
1156 }
1157
1158 /**
1159 * 设置时间字段的分隔符(用于字符串格式的时间)
1160 * @param timeSeparator 分隔符字符串
1161 */
1162 public void setTimeSeparator(String timeSeparator) {
1163 this.timeSeparator = timeSeparator;
1164 }
1165
1166 /**
1167 * 正则表达式引用处理方法,源自 JDK @link java.util.regex.Pattern#quote(String)
1168 */
1169 private String patternQuote(String s) {
1170 int slashEIndex = s.indexOf("\\E");
1171 if (slashEIndex == -1)
1172 return "\\Q" + s + "\\E";
1173
1174 StringBuilder sb = new StringBuilder(s.length() * 2);
1175 sb.append("\\Q");
1176 slashEIndex = 0;
1177 int current = 0;
1178 while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
1179 sb.append(s.substring(current, slashEIndex));
1180 current = slashEIndex + 2;
1181 sb.append("\\E\\\\E\\Q");
1182 }
1183 sb.append(s.substring(current, s.length()));
1184 sb.append("\\E");
1185 return sb.toString();
1186 }
1187
1188 public String toString() {
1189 DecimalFormat df = new DecimalFormat("00");
1190 return new StringBuffer().append(fields[DAY]).append(", ")
1191 .append(df.format(fields[HOUR])).append(timeSeparator)
1192 .append(df.format(fields[MINUTE])).append(timeSeparator)
1193 .append(df.format(fields[SECOND]))
1194 .toString();
1195 }
1196
1197 public int hashCode() {
1198 final int PRIME = 31;
1199 int result = 1;
1200 result = PRIME * result + Arrays.hashCode(fields);
1201 return result;
1202 }
1203
1204 public boolean equals(Object obj) {
1205 if (this == obj)
1206 return true;
1207 if (obj == null)
1208 return false;
1209 if (getClass() != obj.getClass())
1210 return false;
1211 final Time other = (Time) obj;
1212 if (!Arrays.equals(fields, other.fields)) {
1213 return false;
1214 }
1215 return true;
1216 }
1217 }
1218
1219
1220
1221
1222 ISBN(国际标准书号)的校验
1223
1224 public class Test {
1225
1226 public static void main(String[] args) {
1227 System.out.println("9787302155638 " + ISBN.checkISBN("9787302155638"));
1228 System.out.println("7564105607 " + ISBN.checkISBN("7564105607"));
1229 System.out.println("730213880X " + ISBN.checkISBN("730213880X"));
1230 System.out.println("7302138800 " + ISBN.checkISBN("7302138800"));
1231 System.out.println("9790000000000 " + ISBN.checkISBN("9790000000000"));
1232 try {
1233 System.out.println(ISBN.checkISBN("9770000000000"));
1234 }catch(Exception e) {
1235 System.out.println("9770000000000 " + e.getMessage());
1236 }
1237 try {
1238 System.out.println(ISBN.checkISBN("123456545"));
1239 }catch(Exception e) {
1240 System.out.println("123456545 " + e.getMessage());
1241 }
1242 }
1243 }
1244
1245 public final class ISBN {
1246
1247 /**
1248 * 根据输入的ISBN号,检验ISBN的有效性。依据 GB/T 5795-2006 和 ISO 2108:2005 ISBN
1249 * 10位标准和13位标准实现(13位标准自2007年1月1日开始实行,在此之前采用10位标准)。
1250 *
1251 * @param String isbn:需要进行校验的ISBN字符串
1252 * @return true:所输入的ISBN校验正确;<br/> false:所输入的ISBN校验错误
1253 */
1254 public static boolean checkISBN(String isbn) {
1255
1256 int count = 0;
1257 int checkBitInt = 0;
1258
1259 // 将ISBN数据全取大写字母
1260 //isbn = isbn.toUpperCase();
1261
1262 char[] cs = isbn.toCharArray();
1263 switch (isbn.length()) {
1264 case 10:
1265 // ****************************************************************
1266 // 当ISBN为10位时,进行的校验,用于2007年1月1日前的出版物
1267 // 数据格式:从左至右前9位为ISBN数据,第10位为校验位
1268 // 校验方法:
1269 // (1) 从左至右将前9位数据从10开始至2进行编号,作为位权
1270 // (2) 将9位数据与各位位权进行加权,并求其9位和(称为加权和,记作M)
1271 // (3) 第10位校验位计算方法,校验位为C:
1272 // M + C ≡ 0 (mod 11)
1273 // C为10时,记作“X”
1274 // ****************************************************************
1275
1276 // 取出前9位数字进行加权和计算
1277 for (int i = 0; i < 9; i++) {
1278 // 若前9位数据中有非数字字符,则抛出异常
1279 if (cs < '0' || cs > '9') {
1280 throw new ISBNFormatException("ISBN " + isbn +
1281 " 第 " + (i + 1) + " 位中出现非法字符 " + cs);
1282 }
1283
1284 int c = cs - '0';
1285 // 求加权和
1286 count += c * (10 - i);
1287 }
1288
1289 // 取出校验位数据0~9和X符合校验字符要求
1290 if (cs[9] >= '0' && cs[9] <= '9') {
1291 checkBitInt = cs[9] - '0';
1292 } else if (cs[9] == 'X' || cs[9] == 'x') {
1293 // 校验位中的“X”表示数据“10”
1294 checkBitInt = 10;
1295 } else {
1296 // 非0~9或X时抛出异常
1297 throw new ISBNFormatException("ISBN " + isbn +
1298 " 第 10 位中出现非法字符 " + cs[9]);
1299 }
1300
1301 // 进行校验
1302 if ((count + checkBitInt) % 11 == 0) {
1303 return true; // 校验成功
1304 } else {
1305 return false; // 校验失败
1306 }
1307 case 13:
1308 // ****************************************************************
1309 // 当ISBN为13位时,进行的校验,用于2007年1月1日后的出版物
1310 // 数据格式:从左至右前12位为ISBN数据,第13位为校验位
1311 // 校验方法:
1312 // (1) 从左至右将前12位数的取其奇位数和和偶位数和
1313 // (2) 将偶位数和乘3,并其与奇位数和的和,得加权和
1314 // (3) 第13位校验位计算方法,校验位为C:
1315 // M + C ≡ 0 (mod 10)
1316 // ****************************************************************
1317
1318 // ISBN为13位数据时,前3位目前只能是“978”(已实行)或“979”(暂未实行)
1319 if (!isbn.startsWith("978") && !isbn.startsWith("979")) {
1320 throw new ISBNFormatException("ISBN-13 格式不符合标准");
1321 }
1322 // 取出前12位数字进行加权和计算
1323 int countEven = 0;
1324 int countOdd = 0;
1325 for (int i = 0; i < 12; i++) {
1326 int c = cs - '0';
1327 // 若前12位数据中有非数字字符,则抛出异常
1328 if (c < 0 || c > 9) {
1329 throw new ISBNFormatException("ISBN " + isbn +
1330 " 第 " + (i + 1) + " 位中出现非法字符 " + cs);
1331 }
1332 // 分别计算奇位数和偶位数的和
1333 if ((i & 0x1) == 0) {
1334 countOdd += c;
1335 } else {
1336 countEven += c;
1337 }
1338 }
1339 // 求加权和
1340 count = countOdd + (countEven * 3);
1341
1342 // 取出校验位数据
1343 if (cs[12] < '0' || cs[12] > '9') {
1344 // 校验位为非0~9字符时,抛出异常
1345 throw new ISBNFormatException("ISBN " + isbn
1346 + " 第 13 位中出现非法字符 " + cs[12]);
1347 }
1348
1349 checkBitInt = cs[12] - '0';
1350 // 进行校验
1351 if ((count + checkBitInt) % 10 == 0) {
1352 return true; // 校验成功
1353 } else {
1354 return false; // 校验失败
1355 }
1356 default:
1357 // ISBN为非10位或13位时抛出异常
1358 throw new ISBNFormatException("ISBN 格式不符合标准");
1359 }
1360 }
1361 }
1362
1363
1364
1365
1366
1367
1368 import java.util.ArrayList;
1369 import java.util.Iterator;
1370 import java.util.LinkedHashMap;
1371 import java.util.List;
1372 import java.util.Map;
1373
1374 /**
1375 * JSON utility class
1376 *
1377 * @since 2008-04-21
1378 */
1379 public class Json {
1380
1381 // test
1382 public static void main(String[] args) {
1383 Json json1 = new Json();
1384 json1.add("totalCount", 2);
1385 json1.add("isTest", true);
1386
1387 Json json_a = new Json();
1388 json_a.add("menuid", 1);
1389 json_a.add("menuname", "testmenu");
1390 json1.add("topics", json_a);
1391
1392 Json json_b = new Json();
1393 json_b.add("menuid", 2);
1394 json_b.add("menuname", "testmenu");
1395 json1.add("topics", json_b);
1396 System.out.println(json1.toString());
1397 }
1398
1399 private Map map = new LinkedHashMap();
1400
1401 /**
1402 * 添加一个 JSON 属性,值为一个字符串,重复添加时产生数组<p/>
1403 *
1404 * add("name", "value");<br/>
1405 * 添加一个字符串,产生的 JSON 如:{"name":"value"}<p/>
1406 *
1407 * add("name", "value1");<br/>
1408 * add("name", "value2");<br/>
1409 * 添加两个同属性的字符串,产生的 JSON 如:{"name":["value1", "value2"]}<p/>
1410 *
1411 * @param key JSON 属性名
1412 * @param str 字符串格式的属性值
1413 */
1414 public void add(String key, String value) {
1415 addElement(key, value);
1416 }
1417
1418 public void add(String key, int num) {
1419 addElement(key, new Integer(num));
1420 }
1421
1422 public void add(String key, boolean b) {
1423 addElement(key, new Boolean(b));
1424 }
1425
1426 /**
1427 * 添加一个 JSON 属性,值为一个 JSON,重复添加时产生 JSON 数组<p/>
1428 *
1429 * Json json1 = new Json();<br/>
1430 * json1.add("name1", "value1");<br/>
1431 * json1.add("name2", "value2");<br/>
1432 * Json json = new Json();<br/>
1433 * json.add("message", json1);<br/>
1434 * 添加一个 JSON,产生的 JSON 如:{"message":{"name1":"value1", "name2":"value2"}}<p/>
1435 *
1436 * Json json1 = new Json();<br/>
1437 * json1.add("name1", "value1");<br/>
1438 * json1.add("name2", "value2");<br/>
1439 * Json json2 = new Json();<br/>
1440 * json2.add("name1", "value3");<br/>
1441 * json2.add("name2", "value4");<br/>
1442 * Json json = new Json();<br/>
1443 * json.add("message", json1);<br/>
1444 * json.add("message", json2);<br/>
1445 * 添加两个同属性的 JSON,产生的 JSON 如:{"message":[{"name1":"value1", "name2":"value2"}, {"name1":"value3", "name2":"value4"}]}<p/>
1446 *
1447 * @param key JSON 属性名
1448 * @param json JSON 格式的属性值
1449 */
1450 public void add(String key, Json json) {
1451 addElement(key, json);
1452 }
1453
1454 public String toString() {
1455 StringBuilder sb = new StringBuilder();
1456 sb.append("{");
1457 int k = 0;
1458 for (Iterator i = map.keySet().iterator(); i.hasNext();) {
1459 String key = (String)(i.next());
1460 Object obj = map.get(key);
1461 if (k > 0) {
1462 sb.append(",");
1463 }
1464 appendKey(sb, key);
1465 if (obj instanceof String) {
1466 appendString(sb, (String)obj);
1467 } else if (obj instanceof List) {
1468 appendList(sb, (List)obj);
1469 } else if (obj instanceof Json) {
1470 appendJson(sb, (Json)obj);
1471 } else {
1472 appendOther(sb, obj);
1473 }
1474 k++;
1475 }
1476 sb.append("}");
1477 return sb.toString();
1478 }
1479
1480 private void addElement(String key, Object obj) {
1481 if (!map.containsKey(key)) {
1482 if(obj instanceof Json) {
1483 List list = new ArrayList();
1484 list.add(obj);
1485 map.put(key, list);
1486 } else {
1487 map.put(key, obj);
1488 }
1489 return;
1490 }
1491
1492 Object o = map.remove(key);
1493
1494 if (o instanceof List) {
1495 ((List)o).add(obj);
1496 map.put(key, o);
1497 return;
1498 }
1499
1500 // o is a String
1501 List list = new ArrayList();
1502 list.add(o);
1503 list.add(obj);
1504 map.put(key, list);
1505 }
1506
1507 /**
1508 * Append JSON property name
1509 *
1510 * @param sb
1511 * @param key
1512 */
1513 private void appendKey(StringBuilder sb, String key) {
1514 sb.append("\"").append(key).append("\":");
1515 }
1516
1517 /**
1518 * Append JSON property value that is a String
1519 *
1520 * @param sb
1521 * @param str
1522 */
1523 private void appendString(StringBuilder sb, String str) {
1524 sb.append("\"").append(str).append("\"");
1525 }
1526
1527 /**
1528 * Append JSON property value that is a Integer
1529 *
1530 * @param sb
1531 * @param num
1532 */
1533 private void appendOther(StringBuilder sb, Object obj) {
1534 sb.append(obj);
1535 }
1536
1537 /**
1538 * Append JSON property value that is a List
1539 *
1540 * @param sb
1541 * @param list
1542 */
1543 private void appendList(StringBuilder sb, List list) {
1544 sb.append("[");
1545 for (int j = 0, m = list.size(); j < m; j++) {
1546 if (j > 0) {
1547 sb.append(",");
1548 }
1549 Object obj = list.get(j);
1550 if (obj instanceof String) {
1551 appendString(sb, (String)obj);
1552 } else if (obj instanceof Json) {
1553 appendJson(sb, (Json)obj);
1554 } else {
1555 appendOther(sb, obj);
1556 }
1557 }
1558 sb.append("]");
1559 }
1560
1561 /**
1562 * Append JSON property value that is a JSON
1563 *
1564 * @param sb
1565 * @param json
1566 */
1567 private void appendJson(StringBuilder sb, Json json) {
1568 sb.append(json.toString());
1569 }
1570 }
1571
1572
1573
1574 /**
1575 * 从指定的字符串中提取Email
1576 * content 指定的字符串
1577 */
1578 public static String parse(String content) {
1579 String email = null;
1580 if (content==null || content.length()<1) {
1581 return email;
1582 }
1583 //找出含有@
1584 int beginPos;
1585 int i;
1586 String token = "@";
1587 String preHalf="";
1588 String sufHalf = "";
1589
1590 beginPos = content.indexOf(token);
1591 if (beginPos>-1) {
1592 //前项扫描
1593 String s = null;
1594 i= beginPos;
1595 while(i>0) {
1596 s = content.substring(i-1,i);
1597 if (isLetter(s))
1598 preHalf = s+preHalf;
1599 else
1600 break;
1601 i--;
1602 }
1603 //后项扫描
1604 i= beginPos+1;
1605 while( i<content.length()) {
1606 s = content.substring(i,i+1);
1607 if (isLetter(s))
1608 sufHalf = sufHalf +s;
1609 else
1610 break;
1611 i++;
1612 }
1613 //判断合法性
1614 email = preHalf + "@" + sufHalf;
1615 if (isEmail(email)) {
1616 return email;
1617 }
1618 }
1619 return null;
1620 }
1621
1622 /**
1623 * 判断是不是合法Email
1624 * email Email地址
1625 */
1626 public static boolean isEmail(String email) {
1627 try {
1628 if (email==null || email.length()<1 || email.length()>256) {
1629 return false;
1630 }
1631
1632 String check = "^([0-9a-zA-Z]+[_.0-9a-zA-Z-]+)@([a-zA-Z0-9-]+[.])+([a-zA-Z]{2,3})$";
1633 Pattern regex = Pattern.compile(check);
1634 Matcher matcher = regex.matcher(email);
1635 boolean isMatched = matcher.matches();
1636 if(isMatched) {
1637 return true;
1638 } else {
1639 return false;
1640 }
1641 } catch (RuntimeException e) {
1642 return false;
1643 }
1644 }
1645
1646 /**
1647 * 判断是不是合法字符
1648 * c 要判断的字符
1649 */
1650 public static boolean isLetter(String c) {
1651 boolean result = false;
1652
1653 if (c==null || c.length()<0) {
1654 return false;
1655 }
1656 //a-z
1657 if (c.compareToIgnoreCase("a")>=0 && c.compareToIgnoreCase("z")<=0) {
1658 return true;
1659 }
1660 //0-9
1661 if (c.compareToIgnoreCase("0")>=0 && c.compareToIgnoreCase("9")<=0) {
1662 return true;
1663 }
1664 //. - _
1665 if (c.equals(".") || c.equals("-") || c.equals("_") ) {
1666 return true;
1667 }
1668 return result;
1669 }
1670
1671
1672
1673 /**
1674 * 列出某文件夹及其子文件夹下面的文件,并可根据扩展名过滤
1675 *
1676 * @param path
1677 */
1678 public static void list(File path)
1679 {
1680 if (!path.exists())
1681 {
1682 System.out.println("文件名称不存在!");
1683 }
1684 else
1685 {
1686 if (path.isFile())
1687 {
1688 if (path.getName().toLowerCase().endsWith(".pdf")
1689 || path.getName().toLowerCase().endsWith(".doc")
1690 || path.getName().toLowerCase().endsWith(".html")
1691 || path.getName().toLowerCase().endsWith(".htm"))
1692 {
1693 System.out.println(path);
1694 System.out.println(path.getName());
1695 }
1696 }
1697 else
1698 {
1699 File[] files = path.listFiles();
1700 for (int i = 0; i < files.length; i++)
1701 {
1702 list(files);
1703 }
1704 }
1705 }
1706 }
1707
1708
1709
1710
1711 /**
1712 * 拷贝一个目录或者文件到指定路径下
1713 *
1714 * @param source
1715 * @param target
1716 */
1717 public static void copy(File source, File target)
1718 {
1719 File tarpath = new File(target, source.getName());
1720 if (source.isDirectory())
1721 {
1722 tarpath.mkdir();
1723 File[] dir = source.listFiles();
1724 for (int i = 0; i < dir.length; i++)
1725 {
1726 copy(dir, tarpath);
1727 }
1728 }
1729 else
1730 {
1731 try
1732 {
1733 InputStream is = new FileInputStream(source);
1734 OutputStream os = new FileOutputStream(tarpath);
1735 byte[] buf = new byte[1024];
1736 int len = 0;
1737 while ((len = is.read(buf)) != -1)
1738 {
1739 os.write(buf, 0, len);
1740 }
1741 is.close();
1742 os.close();
1743 }
1744 catch (FileNotFoundException e)
1745 {
1746 e.printStackTrace();
1747 }
1748 catch (IOException e)
1749 {
1750 e.printStackTrace();
1751 }
1752 }
1753 }
1754
1755
1756
1757
1758 Java日期格式化及其使用例子
1759 1 SimpleDateFormat担当重任,怎样格式化都行
1760
1761 import java.util.Date;
1762 import java.text.SimpleDateFormat;
1763 public class Demo
1764 {
1765 public static void main(String[] args)
1766 {
1767 Date now=new Date();
1768 SimpleDateFormat f=newSimpleDateFormat("今天是"+"yyyy年MM月dd日 E kk点mm分");
1769 System.out.println(f.format(now));
1770
1771 f=new SimpleDateFormat("a hh点mm分ss秒");
1772 System.out.println(f.format(now));
1773 }
1774 }
1775
1776
1777 2 从字符串到日期类型的转换:
1778
1779 import java.util.Date;
1780 import java.text.SimpleDateFormat;
1781 import java.util.GregorianCalendar;
1782 import java.text.*;
1783 publicclass Demo
1784 {
1785 public static void main(String[] args)
1786 {
1787 String strDate="2005年04月22日";
1788 //注意:SimpleDateFormat构造函数的样式与strDate的样式必须相符
1789 SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy年MM月dd日");
1790 //必须捕获异常
1791
1792 try
1793 {
1794 Date date=simpleDateFormat.parse(strDate);
1795 System.out.println(date);
1796 }
1797 catch(ParseException px)
1798 {
1799 px.printStackTrace();
1800 }
1801 }
1802 }
1803
1804
1805 3 将毫秒数换转成日期类型
1806
1807 import java.util.Date;
1808 import java.text.SimpleDateFormat;
1809 import java.util.GregorianCalendar;
1810 import java.text.*;
1811 public class Demo
1812 {
1813 public static void main(String[] args)
1814 {
1815 long now=System.currentTimeMillis();
1816 System.out.println("毫秒数:"+now);
1817 Date dNow=new Date(now);
1818 System.out.println("日期类型:"+dNow);
1819 }
1820 }
1821
1822
1823 这3例源自http://blog.csdn.net/zhoujian2003/archive/2005/04/22/358363.aspx
1824
1825 4 获取系统时期和时间,转换成SQL格式后更新到数据库
1826 (http://blog.csdn.net/netrope/archive/2005/11/19/532729.aspx)
1827
1828 java.util.Date d=new java.util.Date(); //获取当前系统的时间
1829
1830 //格式化日期
1831
1832 new java.text.SimpleDateFormat s= new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1833
1834 String dateStr = s.format(d); //转为字符串
1835
1836 使用RS更新数据库,仍然要用rs.updateString,而不是rs.updateDade。
1837 rs.updateString("regtime",dateStr); //regtime字段为datetime类型的
1838 下面两例源自 http://blog.csdn.net/kingter520/archive/2004/10/27/155435.aspx
1839
1840 5 按本地时区输出当前日期
1841
1842 Date myDate = new Date();
1843 System.out.println(myDate.toLocaleString());
1844 输出结果为:
1845 2003-5-30
1846
1847
1848 6 如何格式化小数
1849
1850 DecimalFormat df = new DecimalFormat(",###.00");
1851 double aNumber = 33665448856.6568975;
1852 String result = df.format(aNumber);
1853 Sytem. out.println(result);
1854
1855
1856 输出结果为:
1857 33,665,448,856.66
1858
1859 其他:获取毫秒时间 System.currentTimeMillis();
1860
1861 7 在数据库里的日期只以年-月-日的方式输出
1862 (http://blog.csdn.net/zzsxvzzsxv/archive/2007/08/27/1761004.aspx)
1863 定义日期格式:SimpleDateFormat sdf = new SimpleDateFormat(yy-MM-dd);
1864 sql语句为:String sqlStr = "select bookDate from roomBook where bookDate between '2007-4-10' and '2007-4-25'";
1865 输出:
1866 System.out.println(df.format(rs.getDate("bookDate")));
1867
1868
1869
1870
1871
1872 Java中的鼠标和键盘事件
1873 1、使用MouseListener借口处理鼠标事件
1874 鼠标事件有5种:按下鼠标键,释放鼠标键,点击鼠标键,鼠标进入和鼠标退出
1875 鼠标事件类型是MouseEvent,主要方法有:
1876 getX(),getY() 获取鼠标位置
1877 getModifiers() 获取鼠标左键或者右键
1878 getClickCount() 获取鼠标被点击的次数
1879 getSource() 获取鼠标发生的事件源
1880 事件源获得监视器的方法是addMouseListener(),移去监视器的方法是removeMouseListener()
1881 处理事件源发生的时间的事件的接口是MouseListener 接口中有如下的方法
1882 mousePressed(MouseEvent) 负责处理鼠标按下事件
1883 mouseReleased(MouseEvent) 负责处理鼠标释放事件
1884 mouseEntered(MouseEvent) 负责处理鼠标进入容器事件
1885 mouseExited(MouseEvent) 负责处理鼠标离开事件
1886 mouseClicked(MouseEvent) 负责处理点击事件
1887 2、使用MouseMotionListener接口处理鼠标事件
1888 事件源发生的鼠标事件有2种:拖动鼠标和鼠标移动
1889 鼠标事件的类型是MouseEvent
1890 事件源获得监视器的方法是addMouseMotionListener()
1891 处理事件源发生的事件的接口是MouseMotionListener 接口中有如下的方法
1892 mouseDragged() 负责处理鼠标拖动事件
1893 mouseMoved() 负责处理鼠标移动事件
1894 3、控制鼠标的指针形状
1895 setCursor(Cursor.getPreddfinedCursor(Cursor.鼠标形状定义)) 鼠标形状定义见(书 P 210)
1896 4、键盘事件
1897 键盘事件源使用addKeyListener 方法获得监视器
1898 键盘事件的接口是KeyListener 接口中有3个方法
1899 public void keyPressed(KeyEvent e) 按下键盘按键
1900 public void keyReleased(KeyEvent e) 释放键盘按键
1901
1902
1903
1904
1905
1906 public class IsChineseOrEnglish {
1907 // GENERAL_PUNCTUATION 判断中文的“号
1908 // CJK_SYMBOLS_AND_PUNCTUATION 判断中文的。号
1909 // HALFWIDTH_AND_FULLWIDTH_FORMS 判断中文的,号
1910 public static boolean isChinese(char c) {
1911 Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
1912 if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
1913 || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
1914 || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
1915 || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
1916 || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
1917 || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS){
1918 return true;
1919 }
1920 return false;
1921 }
1922 public static void isChinese(String strName) {
1923 char[] ch = strName.toCharArray();
1924 for (int i = 0; i < ch.length; i++) {
1925 char c = ch;
1926 if(isChinese(c)==true){
1927 System.out.println(isChinese(c));
1928 return;
1929 }else{
1930 System.out.println(isChinese(c));
1931 return ;
1932 }
1933 }
1934 }
1935
1936 public static void main(String[] args){
1937
1938 isChinese("zhongguo");
1939 isChinese("中国");
1940 }
1941
1942 }
1943
1944
1945
1946
1947
1948 MD5和一个可逆加密算法相接合的加密和解密程序
1949 比较简单。
1950 [code={0}]
1951 import java.security.MessageDigest;
1952 /**
1953 *先通过MD5加密之后,再来一次可逆的加密。
1954 *顺序可以调整,可以选择先用可逆加密,然后再用MD5加密
1955 */
1956 public class MD5andKL{
1957 //MD5加码。32位
1958 public static String MD5(String inStr) {
1959 MessageDigest md5 = null;
1960 try {
1961 md5 = MessageDigest.getInstance("MD5");
1962 } catch (Exception e) {
1963 System.out.println(e.toString());
1964 e.printStackTrace();
1965 return "";
1966 }
1967 char[] charArray = inStr.toCharArray();
1968 byte[] byteArray = new byte[charArray.length];
1969
1970 for (int i = 0; i < charArray.length; i++)
1971 byteArray = (byte) charArray;
1972
1973 byte[] md5Bytes = md5.digest(byteArray);
1974
1975 StringBuffer hexValue = new StringBuffer();
1976
1977 for (int i = 0; i < md5Bytes.length; i++) {
1978 int val = ((int) md5Bytes) & 0xff;
1979 if (val < 16)
1980 hexValue.append("0");
1981 hexValue.append(Integer.toHexString(val));
1982 }
1983
1984 return hexValue.toString();
1985 }
1986
1987 //可逆的加密算法
1988 public static String KL(String inStr){
1989 //String s = new String(inStr);
1990 char[] a = inStr.toCharArray();
1991 for (int i = 0;i <a.length;i++) {
1992 a = (char)(a^'t');
1993 }
1994 String s=new String(a);
1995 return s;
1996 }
1997 //加密后解密
1998 public static String JM(String inStr){
1999 char[] a=inStr.toCharArray();
2000 for (int i = 0;i <a.length;i++) {
2001 a= (char)(a^'t');
2002 }
2003 String k=new String(a);
2004 return k;
2005 }
2006 //测试主函数
2007 public static void main (String args[]){
2008 String s = new String("admin");
2009 System.out.println("原始:"+s);
2010 System.out.println("MD5后:"+MD5(s));
2011 System.out.println("MD5后再加密:"+KL(MD5(s)));
2012 System.out.println("解密为MD5后的:"+JM(KL(MD5(s))));
2013 }
2014 }
2015 [/code]
2016
2017
2018
2019 /**
2020 * 取得服务器当前的各种具体时间
2021 * 回车:日期时间
2022 */
2023
2024 import java.util.*;
2025
2026 public class GetNowDate{
2027 Calendar calendar = null;
2028
2029 public GetNowDate(){
2030 calendar = Calendar.getInstance();
2031 calendar.setTime(new Date());
2032 }
2033
2034 public int getYear(){
2035 return calendar.get(Calendar.YEAR);
2036 }
2037
2038 public int getMonth(){
2039 return 1 + calendar.get(Calendar.MONTH);
2040 }
2041
2042 public int getDay(){
2043 return calendar.get(Calendar.DAY_OF_MONTH);
2044 }
2045
2046 public int getHour(){
2047 return calendar.get(Calendar.HOUR_OF_DAY);
2048 }
2049
2050 public int getMinute(){
2051 return calendar.get(Calendar.MINUTE);
2052 }
2053
2054 public int getSecond(){
2055 return calendar.get(Calendar.SECOND);
2056 }
2057
2058 public String getDate(){
2059 return getMonth()+"/"+getDay()+"/"+getYear();
2060 }
2061
2062 public String getTime(){
2063 return getHour()+":"+getMinute()+":"+getSecond();
2064 }
2065
2066 public String getDate2(){
2067 String yyyy="0000", mm="00", dd="00";
2068 yyyy = yyyy + getYear();
2069 mm = mm + getMonth();
2070 dd = dd + getDay();
2071 yyyy = yyyy.substring(yyyy.length()-4);
2072 mm = mm.substring(mm.length()-2);
2073 dd = dd.substring(dd.length()-2);
2074 return yyyy + "/" + mm + "/" + dd;
2075 }
2076
2077 public String getTime2(){
2078 String hh="00", mm="00", ss="00";
2079 hh = hh + getHour();
2080 mm = mm + getMinute();
2081 ss = ss + getSecond();
2082 hh = hh.substring(hh.length()-2, hh.length());
2083 mm = mm.substring(mm.length()-2, mm.length());
2084 ss = ss.substring(ss.length()-2, ss.length());
2085 return hh + ":" + mm + ":" + ss;
2086 }
2087 }
2088
2089
2090
2091
2092
2093 /**
2094 * 用半角的特殊符号代替全角的特殊符号
2095 * 防止特殊字符在传输参数时出现错误
2096 *
2097 */
2098
2099 public class ReplaceStrE{
2100 public static String rightToError(String ss){
2101 String strs;
2102 String strs1;
2103 String strs2;
2104 String strs3;
2105 String strs4;
2106 try{
2107 strs = ss.replace('#','#');
2108 }
2109 catch(Exception ex){
2110 return ss;
2111 }
2112
2113 try{
2114 strs1 = strs.replace('"','"');
2115 }
2116 catch(Exception ex){
2117 return strs;
2118 }
2119
2120 try{
2121 strs2 = strs1.replace(' ','&');
2122 }
2123 catch(Exception ex){
2124 return strs1;
2125 }
2126
2127 try{
2128 strs3 = strs2.replace('+','+');
2129 }
2130 catch(Exception ex){
2131 return strs2;
2132 }
2133
2134 try{
2135 strs4 = strs3.replace(''','\'');
2136 }
2137 catch(Exception ex){
2138 return ss;
2139 }
2140 return strs4;
2141 }
2142 }
2143
2144
2145
2146
2147 /**
2148 * Big5字与Unicode的互换
2149 * 转换后的正常字型
2150 */
2151
2152 import java.io.*;
2153
2154 public class MyUtil{
2155 public static String big5ToUnicode(String s){
2156 try{
2157 return new String(s.getBytes("ISO8859_1"), "Big5");
2158 }
2159 catch (UnsupportedEncodingException uee){
2160 return s;
2161 }
2162 }
2163
2164 public static String UnicodeTobig5(String s){
2165 try{
2166 return new String(s.getBytes("Big5"), "ISO8859_1");
2167 }
2168 catch (UnsupportedEncodingException uee){
2169 return s;
2170 }
2171 }
2172
2173 public static String toHexString(String s){
2174 String str="";
2175 for (int i=0; i<s.length(); i++){
2176 int ch=(int)s.charAt(i);
2177 String s4="0000"+Integer.toHexString(ch);
2178 str=str+s4.substring(s4.length()-4)+" ";
2179 }
2180 return str;
2181 }
2182 }
2183
2184
2185
2186
2187
2188 import java.io.*;
2189 import java.util.ArrayList;
2190 import java.util.List;
2191 public class FileCopy {
2192 private String message = "";
2193 public String getMessage() {
2194 return message;
2195 }
2196 public void setMessage(String message) {
2197 this.message = message;
2198 }
2199 /**
2200 * 将源文件拷贝到目标文件
2201 *
2202 * @param src
2203 * 写源文件地址,需文件名
2204 * @param des
2205 * 写目标文件地址,无需文件名
2206 */
2207 public boolean copyFile(String src, String des) {
2208 File srcFile = new File(src);
2209 File desDir = new File(des);
2210 File desFile = new File(des + "/" + srcFile.getName());
2211 // 判断源文件是否存在
2212 if (!srcFile.exists()) {
2213 this.setMessage("源文件不存在!");
2214 return false;
2215 } else if (!srcFile.isFile()) {
2216 this.setMessage("源文件格式错!");
2217 return false;
2218 }
2219 // 判断源文件是否存在
2220 if (!desDir.exists()) {
2221 this.setMessage("目标目录不存在!");
2222 return false;
2223 } else if (!desDir.isDirectory()) {
2224 this.setMessage("不是有效的目录!");
2225 return false;
2226 }
2227 BufferedReader reader = null;
2228 BufferedWriter writer = null;
2229 String str;
2230 try {
2231 reader = new BufferedReader(new FileReader(srcFile));
2232 writer = new BufferedWriter(new FileWriter(desFile));
2233 // 判断目标文件是否存在及其格式,不存在就创建,格式不对先删除,存在就替代
2234 if (!desFile.exists() || !desFile.isFile()) {
2235 if (desFile.exists()) {
2236 desFile.delete();
2237 }
2238 desFile.createNewFile();
2239 }
2240 // 从源文件读取数据,并写入目标文件
2241 str = reader.readLine();
2242 while (str != null) {
2243 writer.write(str);
2244 writer.newLine();
2245 str = reader.readLine();
2246 }
2247 } catch (IOException e) {
2248 this.setMessage(e.getMessage());
2249 return false;
2250 } finally {
2251 if (reader != null) {
2252 try {
2253 reader.close();
2254 } catch (IOException e) {
2255 this.setMessage(e.getMessage());
2256 }
2257 }
2258 if (writer != null) {
2259 try {
2260 writer.close();
2261 } catch (IOException e) {
2262 this.setMessage(e.getMessage());
2263 }
2264 }
2265 }
2266 return true;
2267 }
2268 private List fileList = new ArrayList();
2269
2270 /**
2271 * 列出所有文件
2272 * @param srcFile
2273 */
2274 private void file(File srcFile) {
2275 if (srcFile.isDirectory()) {
2276 String[] files = srcFile.list();
2277
2278 for (int i = 0; i < files.length; i++) {
2279 File f = new File(srcFile + "/" + files);
2280 // 如果是文件加入列表,否则递归列出
2281 if (f.isFile()) {
2282 fileList.add(f);
2283 } else
2284 file(f);
2285 }
2286 }else this.setMessage(srcFile.getAbsolutePath()+"不是目录");
2287 }
2288 /**
2289 * 建立目录
2290 * @param des
2291 * @throws IOException
2292 */private void mkdir(File des) {
2293 if (!des.exists() || !des.isDirectory()) {
2294 mkdir(des.getParentFile());
2295 if (des.exists()) {
2296 des.delete();
2297 }
2298 des.mkdir();
2299 }
2300 }
2301 /**
2302 * 复制目录 将源目录下所有文件拷贝到目标目录下
2303 * @param src 源目录
2304 * @param des 目标目录
2305 */
2306 public boolean copyDir(String src, String des) {
2307 File srcFile = new File(src);
2308 if (!srcFile.exists()) {
2309 this.setMessage("源目录不存在!");
2310 return false;
2311 } else if (!srcFile.isDirectory()) {
2312 this.setMessage(src+"不是有效的目录!");
2313 return false;
2314 }
2315 file(srcFile);
2316
2317 for (int i = 0; i < fileList.size(); i++) {
2318 String srcName = ((File) fileList.get(i)).getPath();
2319 String desName = srcName.substring(src.length(), srcName.length());
2320 desName = des + desName;
2321 File dir=new File(desName).getParentFile();
2322 mkdir(dir);
2323
2324 if(!copyFile(srcName, dir.getPath())){
2325 return false;
2326 }
2327 }
2328 return true;
2329 }
2330 public static void main(String[] args) {
2331
2332 FileCopy t = new FileCopy();
2333 System.out.println(t.copyFile("D:/aaa.txt","E:"));
2334 String src="D:/asdf";
2335 String des="E:/adf";
2336 System.out.println(t.copyDir(src, des));
2337 System.out.println(t.getMessage());
2338 }
2339
2340 }
2341
2342
2343
2344
2345 /**
2346 * Description: 获取GMT8时间
2347 * @return 将当前时间转换为GMT8时区后的Date
2348 */
2349 public static Date getGMT8Time(){
2350 Date gmt8 = null;
2351 try {
2352 Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"),Locale.CHINESE);
2353 Calendar day = Calendar.getInstance();
2354 day.set(Calendar.YEAR, cal.get(Calendar.YEAR));
2355 day.set(Calendar.MONTH, cal.get(Calendar.MONTH));
2356 day.set(Calendar.DATE, cal.get(Calendar.DATE));
2357 day.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY));
2358 day.set(Calendar.MINUTE, cal.get(Calendar.MINUTE));
2359 day.set(Calendar.SECOND, cal.get(Calendar.SECOND));
2360 gmt8 = day.getTime();
2361 } catch (Exception e) {
2362 System.out.println("获取GMT8时间 getGMT8Time() error !");
2363 e.printStackTrace();
2364 gmt8 = null;
2365 }
2366 return gmt8;
2367 }
2368
2369
2370
2371
2372 import java.io.File;
2373 import java.io.FileInputStream;
2374 import java.io.FileNotFoundException;
2375 import java.io.IOException;
2376 import java.util.Properties;
2377 /**
2378 * ReadProperties.java
2379 * Description: 读取操作属性配置文件
2380 * @author li.b
2381 * @version 2.0
2382 * Jun 26, 2008
2383 */
2384 public class ReadProperties {
2385
2386 /**
2387 * Description: 获取属性配置文件
2388 * @param path 资源文件路径
2389 * @return Properties Object
2390 * @throws FileNotFoundException
2391 * @throws IOException
2392 */
2393 public static Properties getProperties(String path) throws FileNotFoundException, IOException{
2394 Properties props = null;
2395 File file = new File(path);
2396 if(file.exists() && file.isFile()){
2397 props = new Properties();
2398 props.load(new FileInputStream(file));
2399 }else{
2400 System.out.println(file.toString() + "不存在!");
2401 }
2402 return props;
2403 }
2404
2405 /**
2406 * Description: 从属性文件获取值
2407 * @param props Properties Object
2408 * @param key
2409 * @return 通过key匹配到的value
2410 */
2411 public static String getValue(Properties props,String key,String encod){
2412 String result = "";
2413 String en = "";
2414 String localEN = System.getProperty("file.encoding");
2415 if(encod !=null && !encod.equals("") ){
2416 en = encod;
2417 }else{
2418 en = localEN;
2419 }
2420 try {
2421 key = new String(key.getBytes(en),"ISO-8859-1");
2422 result = props.getProperty(key);
2423 if(!result.equals("")){
2424 result = new String(result.getBytes("ISO-8859-1"),en);
2425 }
2426 } catch (Exception e) {
2427 }finally{
2428 if(result == null)result = "";
2429 return result;
2430 }
2431 }
2432
2433 public static String getValue(Properties props,String key){
2434 return getValue(props, key, "");
2435 }
2436
2437 }
2438
2439
2440
2441
2442
2443
2444 import java.lang.reflect.Array;
2445 import java.util.Date;
2446
2447 public class TestCast {
2448
2449 /**
2450 * @param args
2451 */
2452 //public static void main(String[] args) {
2453 /** *//**
2454 *
2455 * 一般情况下数组和数组是不能直接进行转换的,例如:
2456 * Object[] t1={"1","2"};
2457 * String[] t2=(String[])t1;//这里会出现转换错误
2458 *
2459 * 下面提供了一种方式进行转换
2460 */
2461
2462 //1.0测试一般基础类
2463 /* Object[] t1={"1","2","3","4","5"};
2464 String[] m1=(String[])TestCast.cast(t1,String.class);
2465 for(int i=0;i<m1.length;i++)
2466 System.out.println(m1);
2467
2468 //2.0测试复杂对象
2469 Object[] t2={new Date(1000),new Date(2000)};
2470 Date[] m2=(Date[])TestCast.cast(t2,Date.class);
2471 for(int i=0;i<m2.length;i++)
2472 System.out.println(m2.toString());*/
2473 // }
2474
2475
2476 /** *//**
2477 * 将数组array转换成clss代表的类型后返回
2478 * @param array 需要转换的数组
2479 * @param clss 要转换成的类型
2480 * @return 转换后的数组
2481 */
2482 public static Object cast(Object array,Class clss){
2483 if(null==clss)
2484 throw new IllegalArgumentException("argument clss cannot be null");
2485 if(null==array)
2486 throw new IllegalArgumentException("argument array cannot be null");
2487 if(false==array.getClass().isArray())
2488 throw new IllegalArgumentException("argument array must be array");
2489
2490 Object[] src=(Object[])array;
2491 Object[] dest=(Object[])Array.newInstance(clss, src.length);
2492 System.arraycopy(src, 0, dest, 0, src.length);
2493 return dest;
2494 }
2495 }
2496
2497
2498
2499
2500
2501 处理特殊符号的工具类,这个类是从sturts源码里挖出来的
2502 /**
2503 * DealingCharacter.java
2504 * Description:
2505 * @author li.b
2506 * @version 2.0
2507 * Jun 27, 2008
2508 */
2509 public class DealingCharacter {
2510
2511 /**
2512 * Description: 转译特殊符号标签
2513 * @param value 需要处理的字符串
2514 * @return
2515 */
2516 public static String filter(String value)
2517 {
2518 if(value == null || value.length() == 0)
2519 return value;
2520 StringBuffer result = null;
2521 String filtered = null;
2522 for(int i = 0; i < value.length(); i++)
2523 {
2524 filtered = null;
2525 switch(value.charAt(i))
2526 {
2527 case 60: // '<'
2528 filtered = "<";
2529 break;
2530
2531 case 62: // '>'
2532 filtered = ">";
2533 break;
2534
2535 case 38: // '&'
2536 filtered = "&";
2537 break;
2538
2539 case 34: // '"'
2540 filtered = """;
2541 break;
2542
2543 case 39: // '\''
2544 filtered = "'";
2545 break;
2546 }
2547 if(result == null)
2548 {
2549 if(filtered != null)
2550 {
2551 result = new StringBuffer(value.length() + 50);
2552 if(i > 0)
2553 result.append(value.substring(0, i));
2554 result.append(filtered);
2555 }
2556 } else
2557 if(filtered == null)
2558 result.append(value.charAt(i));
2559 else
2560 result.append(filtered);
2561 }
2562
2563 return result != null ? result.toString() : value;
2564 }
2565
2566 public static void main(String[] args) {
2567 System.out.println(DealingCharacter.filter("<HTML>sdfasfas</HTML>"));
2568 }
2569 }
2570
2571
2572
2573
2574
2575 小标签
2576 import java.io.IOException;
2577 import java.util.List;
2578
2579 import javax.servlet.jsp.JspException;
2580 import javax.servlet.jsp.tagext.TagSupport;
2581
2582 import com.formcontent.show.ShowFormTypeOperateDb;
2583 import com.forum.hibernatePrj.Space;
2584 public class OutPrintForumType extends TagSupport{
2585 public int doStartTag() throws JspException
2586 {
2587 String printStr="";
2588 ShowFormTypeOperateDb showtype=new ShowFormTypeOperateDb();
2589 List list=showtype.getForumType();
2590 if(list!=null&&list.size()>0)
2591 {
2592
2593 for(int i=0;i <list.size();i++)
2594 {
2595 Space space=(Space)list.get(i);
2596 if(space!=null)
2597 {
2598 printStr+=" <tr> <td>"+" <div align='left' class='TypeCss'>"+
2599
2600 space.getSpaceName()+" "+space.getSpaceDescription()+" <br/>目前登陆总人数:"+i+" 人访问数:"+i+"人 </div> </td> </tr>"
2601 +" <tr> <td> </td> </tr>";
2602 }
2603 }
2604 }
2605 try {
2606 pageContext.getOut().write(printStr);
2607 } catch (IOException e) {
2608 e.printStackTrace();
2609 }
2610 return super.doStartTag();
2611 }
2612
2613 }
2614
2615
2616
2617
2618
2619
2620 正则表达式用于字符串处理、表单验证等场合,实用高效。现将一些常用的表达式收集于此,以备不时之需。
2621
2622 匹配中文字符的正则表达式: [\u4e00-\u9fa5]
2623 评注:匹配中文还真是个头疼的事,有了这个表达式就好办了
2624
2625 匹配双字节字符(包括汉字在内):[^\x00-\xff]
2626 评注:可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)
2627
2628 匹配空白行的正则表达式:\n\s*\r
2629 评注:可以用来删除空白行
2630
2631 匹配HTML标记的正则表达式: <(\S*?)[^>]*>.*? </\1> | <.*? />
2632 评注:网上流传的版本太糟糕,上面这个也仅仅能匹配部分,对于复杂的嵌套标记依旧无能为力
2633
2634 匹配首尾空白字符的正则表达式:^\s* |\s*$
2635 评注:可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式
2636
2637 匹配Email地址的正则表达式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
2638 评注:表单验证时很实用
2639
2640 匹配网址URL的正则表达式:[a-zA-z]+://[^\s]*
2641 评注:网上流传的版本功能很有限,上面这个基本可以满足需求
2642
2643 匹配帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$
2644 评注:表单验证时很实用
2645
2646 匹配国内电话号码:\d{3}-\d{8} |\d{4}-\d{7}
2647 评注:匹配形式如 0511-4405222 或 021-87888822
2648
2649 匹配腾讯QQ号:[1-9][0-9]{4,}
2650 评注:腾讯QQ号从10000开始
2651
2652 匹配中国邮政编码:[1-9]\d{5}(?!\d)
2653 评注:中国邮政编码为6位数字
2654
2655 匹配身份证:\d{15} |\d{18}
2656 评注:中国的身份证为15位或18位
2657
2658 匹配ip地址:\d+\.\d+\.\d+\.\d+
2659 评注:提取ip地址时有用
2660
2661 匹配特定数字:
2662 ^[1-9]\d*$ //匹配正整数
2663 ^-[1-9]\d*$ //匹配负整数
2664 ^-?[1-9]\d*$ //匹配整数
2665 ^[1-9]\d* |0$ //匹配非负整数(正整数 + 0)
2666 ^-[1-9]\d* |0$ //匹配非正整数(负整数 + 0)
2667 ^[1-9]\d*\.\d* |0\.\d*[1-9]\d*$ //匹配正浮点数
2668 ^-([1-9]\d*\.\d* |0\.\d*[1-9]\d*)$ //匹配负浮点数
2669 ^-?([1-9]\d*\.\d* |0\.\d*[1-9]\d* |0?\.0+ |0)$ //匹配浮点数
2670 ^[1-9]\d*\.\d* |0\.\d*[1-9]\d* |0?\.0+ |0$ //匹配非负浮点数(正浮点数 + 0)
2671 ^(-([1-9]\d*\.\d* |0\.\d*[1-9]\d*)) |0?\.0+ |0$ //匹配非正浮点数(负浮点数 + 0)
2672 评注:处理大量数据时有用,具体应用时注意修正
2673
2674 匹配特定字符串:
2675 ^[A-Za-z]+$ //匹配由26个英文字母组成的字符串
2676 ^[A-Z]+$ //匹配由26个英文字母的大写组成的字符串
2677 ^[a-z]+$ //匹配由26个英文字母的小写组成的字符串
2678 ^[A-Za-z0-9]+$ //匹配由数字和26个英文字母组成的字符串
2679 ^\w+$ //匹配由数字、26个英文字母或者下划线组成的字符串
2680
2681
2682
2683
2684 /**
2685 * 将数组转成字符串 在调试或记录日志时用到
2686 *
2687 * @param array
2688 * @return
2689 */
2690 public static String byte2string(byte[] array) {
2691 StringBuilder sb = new StringBuilder();
2692
2693 sb.append("Length " + array.length + " Content ");
2694
2695 for (int i = 0; i < leng; i++) {
2696 sb = sb.append(String.format("%02X", array)).append(":");
2697 }
2698 int ind = sb.lastIndexOf(":");
2699 sb.delete(ind, ind + 1);
2700 return sb.toString();
2701 }
2702
2703
2704
2705
2706
2707 import java.util.Arrays;
2708 import java.util.Random;
2709
2710 /**
2711 * <code>RandomUtil</code> - Random Tool Class.
2712 * @author SageZk
2713 * @version 1.0
2714 */
2715 public class RandomUtil {
2716
2717 private RandomUtil() {}
2718
2719 private static Random rnd = null;
2720
2721 /**
2722 * 初始化随机数发生器。
2723 */
2724 private static void initRnd() {
2725 if (rnd == null) rnd = new Random();
2726 }
2727
2728 /**
2729 * 计算并返回无重复值的以 <code>min</code> 为下限 <code>max</code> 为上限的随机整数数组。
2730 * @param min 随机整数下限(包含)
2731 * @param max 随机整数上限(包含)
2732 * @param len 结果数组长度
2733 * @return 结果数组
2734 */
2735 public static int[] getLotteryArray(int min, int max, int len) {
2736 //参数校验及性能优化
2737 if (len < 0) return null; //长度小于 0 的数组不存在
2738 if (len == 0) return new int[0]; //返回长度为 0 的数组
2739 if (min > max) { //校正参数 min max
2740 int t = min;
2741 min = max;
2742 max = t;
2743 }
2744 final int LEN = max - min + 1; //种子个数
2745 if (len > LEN) return null; //如果出现 35 选 36 的情况就返回 null
2746 //计算无重复值随机数组
2747 initRnd(); //初始化随机数发生器
2748 int[] seed = new int[LEN]; //种子数组
2749 for (int i = 0, n = min; i < LEN;) seed[i++] = n++; //初始化种子数组
2750 for (int i = 0, j = 0, t = 0; i < len; ++i) {
2751 j = rnd.nextInt(LEN - i) + i;
2752 t = seed;
2753 seed = seed[j];
2754 seed[j] = t;
2755 }
2756 return Arrays.copyOf(seed, len); //注意:copyOf 需要 JRE1.6
2757 }
2758
2759 //Unit Testing
2760 public static void main(String[] args) {
2761 final int N = 10000; //测试次数
2762 for (int i = 0; i < N; ++i) {
2763 int[] la = RandomUtil.getLotteryArray(1, 35, 7);
2764 if (la == null) continue;
2765 for (int v : la) System.out.printf("%0$02d ", v);
2766 System.out.println();
2767 }
2768 }
2769
2770 }
2771
2772
2773
2774
2775
2776 /*
2777 操作属性文件,可以为我们的程序带来更方便的移植性,下面是一个示例,可以读、写、更改属性
2778 读采用了两种方式,一种是采用Properties类,另外一种是采用资源绑定类ResourceBundle类,
2779 下面是源程序,里面有详细的注释:
2780 */
2781 import java.io.FileInputStream;
2782 import java.io.FileOutputStream;
2783 import java.io.InputStream;
2784 import java.util.Properties;
2785 import java.util.ResourceBundle;
2786 /**
2787 *对属性文件(xx.properties)的操作
2788 *注:属性文件一定要放在当前工程的根目录下,也就是放在与src目录在同一个目录下(我的JDevelop
2789 *是这样的)
2790 */
2791 public class OperatePropertiesFile {
2792 public OperatePropertiesFile() {
2793 }
2794 /**
2795 *采用Properties类取得属性文件对应值
2796 *@parampropertiesFileNameproperties文件名,如a.properties
2797 *@parampropertyName属性名
2798 *@return根据属性名得到的属性值,如没有返回""
2799 */
2800 public static String getValueByPropertyName(String propertiesFileName,String propertyName) {
2801 String s="";
2802 Properties p=new Properties();//加载属性文件读取类
2803 FileInputStream in;
2804 try {
2805 //propertiesFileName如test.properties
2806 in = new FileInputStream(propertiesFileName);//以流的形式读入属性文件
2807 p.load(in);//属性文件将该流加入的可被读取的属性中
2808 in.close();//读完了关闭
2809 s=p.getProperty(propertyName);//取得对应的属性值
2810 } catch (Exception e) {
2811 e.printStackTrace();
2812 }
2813 return s;
2814 }
2815 /**
2816 *采用ResourceBundel类取得属性文件对应值,这个只能够读取,不可以更改及写新的属性
2817 *@parampropertiesFileNameWithoutPostfixproperties文件名,不带后缀
2818 *@parampropertyName属性名
2819 *@return根据属性名得到的属性值,如没有返回""
2820 */
2821 public static String getValueByPropertyName_(String propertiesFileNameWithoutPostfix,String propertyName) {
2822 String s="";
2823 //如属性文件是test.properties,那此时propertiesFileNameWithoutPostfix的值就是test
2824 ResourceBundle bundel = ResourceBundle.getBundle(propertiesFileNameWithoutPostfix);
2825 s=bundel.getString(propertyName);
2826 return s;
2827 }
2828 /**
2829 *更改属性文件的值,如果对应的属性不存在,则自动增加该属性
2830 *@parampropertiesFileNameproperties文件名,如a.properties
2831 *@parampropertyName属性名
2832 *@parampropertyValue将属性名更改成该属性值
2833 *@return是否操作成功
2834 */
2835 public static boolean changeValueByPropertyName(String propertiesFileName,String propertyName,String propertyValue) {
2836 boolean writeOK=true;
2837 Properties p=new Properties();
2838 InputStream in;
2839 try {
2840
2841 in = new FileInputStream(propertiesFileName);
2842 p.load(in);//
2843 in.close();
2844 p.setProperty(propertyName,propertyValue);//设置属性值,如不属性不存在新建
2845 //p.setProperty("testProperty","testPropertyValue");
2846 FileOutputStream out=new FileOutputStream(propertiesFileName);//输出流
2847 p.store(out,"");//设置属性头,如不想设置,请把后面一个用""替换掉
2848 out.flush();//清空缓存,写入磁盘
2849 out.close();//关闭输出流
2850 } catch (Exception e) {
2851 e.printStackTrace();
2852 }
2853 return writeOK;
2854 }
2855 }
2856
2857
2858
2859
2860 /**
2861 * 如果是null,则返回空字符串,如果是非空值则返回该字符串头尾不为空白字符的字符串
2862 *
2863 * @param str
2864 */
2865 public static String toNoNullTrimedString(String str) {
2866 if (str == null) {
2867 return "";
2868 }
2869 return new String(str.trim());
2870 }
2871
2872 /**
2873 * 如果是null,则返回空字符串,如果是非空值则返回该对象所toString后的字符串
2874 *
2875 * @param obj
2876 */
2877 public static String toNoNullString(Object obj) {
2878 if (obj == null)
2879 return "";
2880 return obj.toString();
2881 }
2882
2883 /**
2884 * 本方法把一个Throwable的StackTrace作为一个字符串输出,以利于对StackTrace的操作。<br />
2885 * 通常用于把抛出的Exception转化成字符串进行后续操作。
2886 */
2887 public static String exceptionToStackTrace(Throwable throwable) {
2888 StringBuffer retu = new StringBuffer();
2889 StackTraceElement[] traces = throwable.getStackTrace();
2890 for (StackTraceElement ste : traces) {
2891 retu.append("\n").append(ste.toString());
2892 }
2893 return retu.substring(1);
2894 }
2895
2896
2897
2898
2899
2900 package com.sipgl.eam.utils;
2901
2902 import java.text.SimpleDateFormat;
2903 import java.util.ArrayList;
2904 import java.util.Calendar;
2905 import java.util.Date;
2906 import java.util.GregorianCalendar;
2907 import java.util.LinkedHashMap;
2908
2909 /**
2910 * 日期公用处理类
2911 *
2912 * @author SongJun
2913 * @version 1.3
2914 */
2915 public class DateUtil {
2916 /**
2917 * 解析一个日期之间的所有月份
2918 *
2919 * @param beginDateStr
2920 * @param endDateStr
2921 * @return
2922 */
2923 public static ArrayList getMonthList(String beginDateStr, String endDateStr) {
2924 // 指定要解析的时间格式
2925 SimpleDateFormat f = new SimpleDateFormat("yyyy-MM");
2926 // 返回的月份列表
2927 String sRet = "";
2928
2929 // 定义一些变量
2930 Date beginDate = null;
2931 Date endDate = null;
2932
2933 GregorianCalendar beginGC = null;
2934 GregorianCalendar endGC = null;
2935 ArrayList list = new ArrayList();
2936
2937 try {
2938 // 将字符串parse成日期
2939 beginDate = f.parse(beginDateStr);
2940 endDate = f.parse(endDateStr);
2941
2942 // 设置日历
2943 beginGC = new GregorianCalendar();
2944 beginGC.setTime(beginDate);
2945
2946 endGC = new GregorianCalendar();
2947 endGC.setTime(endDate);
2948
2949 // 直到两个时间相同
2950 while (beginGC.getTime().compareTo(endGC.getTime()) <= 0) {
2951 sRet = beginGC.get(Calendar.YEAR) + "-"
2952 + (beginGC.get(Calendar.MONTH) + 1);
2953 list.add(sRet);
2954 // 以月为单位,增加时间
2955 beginGC.add(Calendar.MONTH, 1);
2956 }
2957 return list;
2958 } catch (Exception e) {
2959 e.printStackTrace();
2960 return null;
2961 }
2962 }
2963
2964 /**
2965 * 解析一个日期段之间的所有日期
2966 *
2967 * @param beginDateStr
2968 * 开始日期
2969 * @param endDateStr
2970 * 结束日期
2971 * @return
2972 */
2973 public static ArrayList getDayList(String beginDateStr, String endDateStr) {
2974 // 指定要解析的时间格式
2975 SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
2976
2977 // 定义一些变量
2978 Date beginDate = null;
2979 Date endDate = null;
2980
2981 Calendar beginGC = null;
2982 Calendar endGC = null;
2983 ArrayList list = new ArrayList();
2984
2985 try {
2986 // 将字符串parse成日期
2987 beginDate = f.parse(beginDateStr);
2988 endDate = f.parse(endDateStr);
2989
2990 // 设置日历
2991 beginGC = Calendar.getInstance();
2992 beginGC.setTime(beginDate);
2993
2994 endGC = Calendar.getInstance();
2995 endGC.setTime(endDate);
2996 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
2997
2998 // 直到两个时间相同
2999 while (beginGC.getTime().compareTo(endGC.getTime()) <= 0) {
3000
3001 list.add(sdf.format(beginGC.getTime()));
3002 // 以日为单位,增加时间
3003 beginGC.add(Calendar.DAY_OF_MONTH, 1);
3004 }
3005 return list;
3006 } catch (Exception e) {
3007 e.printStackTrace();
3008 return null;
3009 }
3010 }
3011
3012 public static ArrayList getYearList() {
3013 ArrayList list = new ArrayList();
3014 Calendar c = null;
3015 c = Calendar.getInstance();
3016 c.setTime(new Date());
3017 int currYear = Calendar.getInstance().get(Calendar.YEAR);
3018
3019 int startYear = currYear - 5;
3020 int endYear = currYear + 10;
3021 for (int i = startYear; i < endYear; i++) {
3022 list.add(new Integer(i));
3023 }
3024 return list;
3025 }
3026
3027 public static int getCurrYear() {
3028 return Calendar.getInstance().get(Calendar.YEAR);
3029 }
3030
3031 /**
3032 * 得到某一年周的总数
3033 *
3034 * @param year
3035 * @return
3036 */
3037 public static LinkedHashMap getWeekList(int year) {
3038 LinkedHashMap map = new LinkedHashMap();
3039 Calendar c = new GregorianCalendar();
3040 c.set(year, Calendar.DECEMBER, 31, 23, 59, 59);
3041 int count = getWeekOfYear(c.getTime());
3042
3043 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
3044 String dayOfWeekStart = "";
3045 String dayOfWeekEnd = "";
3046 for (int i = 1; i <= count; i++) {
3047 dayOfWeekStart = sdf.format(getFirstDayOfWeek(year, i));
3048 dayOfWeekEnd = sdf.format(getLastDayOfWeek(year, i));
3049 map.put(new Integer(i), "第"+i+"周(从"+dayOfWeekStart + "至" + dayOfWeekEnd+")");
3050 }
3051 return map;
3052
3053 }
3054
3055 /**
3056 * 得到一年的总周数
3057 * @param year
3058 * @return
3059 */
3060 public static int getWeekCountInYear(int year){
3061 Calendar c = new GregorianCalendar();
3062 c.set(year, Calendar.DECEMBER, 31, 23, 59, 59);
3063 int count = getWeekOfYear(c.getTime());
3064 return count;
3065 }
3066
3067 /**
3068 * 取得当前日期是多少周
3069 *
3070 * @param date
3071 * @return
3072 */
3073 public static int getWeekOfYear(Date date) {
3074 Calendar c = new GregorianCalendar();
3075 c.setFirstDayOfWeek(Calendar.MONDAY);
3076 c.setMinimalDaysInFirstWeek(7);
3077 c.setTime(date);
3078
3079 return c.get(Calendar.WEEK_OF_YEAR);
3080 }
3081
3082 /**
3083 * 得到某年某周的第一天
3084 *
3085 * @param year
3086 * @param week
3087 * @return
3088 */
3089 public static Date getFirstDayOfWeek(int year, int week) {
3090 Calendar c = new GregorianCalendar();
3091 c.set(Calendar.YEAR, year);
3092 c.set(Calendar.MONTH, Calendar.JANUARY);
3093 c.set(Calendar.DATE, 1);
3094
3095 Calendar cal = (GregorianCalendar) c.clone();
3096 cal.add(Calendar.DATE, week * 7);
3097
3098 return getFirstDayOfWeek(cal.getTime());
3099 }
3100
3101 /**
3102 * 得到某年某周的最后一天
3103 *
3104 * @param year
3105 * @param week
3106 * @return
3107 */
3108 public static Date getLastDayOfWeek(int year, int week) {
3109 Calendar c = new GregorianCalendar();
3110 c.set(Calendar.YEAR, year);
3111 c.set(Calendar.MONTH, Calendar.JANUARY);
3112 c.set(Calendar.DATE, 1);
3113
3114 Calendar cal = (GregorianCalendar) c.clone();
3115 cal.add(Calendar.DATE, week * 7);
3116
3117 return getLastDayOfWeek(cal.getTime());
3118 }
3119
3120 /**
3121 * 得到某年某月的第一天
3122 * @param year
3123 * @param month
3124 * @return
3125 */
3126 public static Date getFirestDayOfMonth(int year,int month){
3127 month = month-1;
3128 Calendar c = Calendar.getInstance();
3129 c.set(Calendar.YEAR, year);
3130 c.set(Calendar.MONTH, month);
3131
3132 int day = c.getActualMinimum(c.DAY_OF_MONTH);
3133
3134 c.set(Calendar.DAY_OF_MONTH, day);
3135 return c.getTime();
3136
3137 }
3138
3139 /**
3140 * 提到某年某月的最后一天
3141 * @param year
3142 * @param month
3143 * @return
3144 */
3145 public static Date getLastDayOfMonth(int year,int month){
3146 month = month-1;
3147 Calendar c = Calendar.getInstance();
3148 c.set(Calendar.YEAR, year);
3149 c.set(Calendar.MONTH, month);
3150 int day = c.getActualMaximum(c.DAY_OF_MONTH);
3151 c.set(Calendar.DAY_OF_MONTH, day);
3152 return c.getTime();
3153 }
3154
3155 /**
3156 * 取得当前日期所在周的第一天
3157 *
3158 * @param date
3159 * @return
3160 */
3161 public static Date getFirstDayOfWeek(Date date) {
3162 Calendar c = new GregorianCalendar();
3163 c.setFirstDayOfWeek(Calendar.MONDAY);
3164 c.setTime(date);
3165 c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
3166 return c.getTime();
3167 }
3168
3169 /**
3170 * 取得当前日期所在周的最后一天
3171 *
3172 * @param date
3173 * @return
3174 */
3175 public static Date getLastDayOfWeek(Date date) {
3176 Calendar c = new GregorianCalendar();
3177 c.setFirstDayOfWeek(Calendar.MONDAY);
3178 c.setTime(date);
3179 c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
3180 return c.getTime();
3181 }
3182
3183 }
3184
3185
3186
3187
3188
3189
3190 /**
3191 * 为RootPaneContainer组件添加键盘事件
3192 * @param rpc RootPaneContainer组件
3193 * @param action 需要执行的动作
3194 * @param keyName 键的名称
3195 * @param keyCode 键的数字代码
3196 * @param modifiers 任意修饰符的按位或组合
3197 */
3198 public static void registerKeyEvent(RootPaneContainer rpc, Action action, String keyName, int keyCode, int modifiers)
3199 {
3200 JRootPane rp = rpc.getRootPane();
3201 InputMap inputMap = rp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
3202 inputMap.put(KeyStroke.getKeyStroke(keyCode, modifiers), keyName);
3203 rp.getActionMap().put(keyName, action);
3204 }
3205
3206 // 判断一个文件是否为二进制文件
3207 public static boolean isBinary(File file) {
3208 boolean isBinary = false;
3209 try {
3210 FileInputStream fin = new FileInputStream(file);
3211 long len = file.length();
3212 for (int j = 0; j < (int) len; j++) {
3213 int t = fin.read();
3214 if (t < 32 && t != 9 && t != 10 && t != 13) {
3215 isBinary = true;
3216 break;
3217 }
3218 }
3219 } catch (Exception e) {
3220 e.printStackTrace();
3221 }
3222 return isBinary;
3223 }