# 经典JAVA算法题册

返回:数据库 | 返回:java常见方法

# Java的16进制与字符串的相互转换函数

back

/**
 * 将指定 byte 数组以 16 进制的形式打印到控制台
 * @param hint String
 * @param b byte[]
 * @return void
*/
public static void printHexString(String hint, byte[] b) {
 System.out.print(hint);
 for (int i = 0; i < b.length; i++) {
 String hex = Integer.toHexString(b[i] & 0xFF);
 if (hex.length() == 1) {
 hex = '0' + hex;
 }
 System.out.print(hex.toUpperCase() + " ");
 }
 System.out.println("");
}
/**
*
* @param b byte[]
* @return String
*/
public static String Bytes2HexString(byte[] b) {
 String ret = "";
 for (int i = 0; i < b.length; i++) {
 String hex = Integer.toHexString(b[i] & 0xFF);
 if (hex.length() == 1) {
 hex = '0' + hex;
 }
 ret += hex.toUpperCase();
 }
 return ret;
}
/**
* 将两个 ASCII 字符合成一个字节;
* 如:"EF"--> 0xEF
* @param src0 byte
* @param src1 byte
* @return byte
*/
public static byte uniteBytes(byte src0, byte src1) {
 byte _b0 = byte.decode("0x" + new String(new byte[]{src0})).byteValue();
 _b0 = (byte)(_b0 << 4);
 byte _b1 = byte.decode("0x" + new String(new byte[]{src1})).byteValue();
 byte ret = (byte)(_b0 ^ _b1);
 return ret;
}
/**
* 将指定字符串 src,以每两个字符分割转换为 16 进制形式
* 如:"2B44EFD9" --> byte[]{0x2B, 0x44, 0xEF, 0xD9}
* @param src String
* @return byte[]
 */
public static byte[] HexString2Bytes(String src){
 byte[] ret = new byte[8];
 byte[] tmp = src.getBytes();
 for (int i=0; i<8; i++){
 ret[i] = uniteBytes(tmp[i*2], tmp[i*2+1]);
 }
 return ret;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

# JAVA时间格式化处理

back

# 将毫秒转化为日期

back

public static void main(String[] args) {
 new ConvertLong2Date().launchFrame();
}
public String convertL2D(long l) {
 long _l = 0L;
 Date _d = null;
 SimpleDateFormat _sdf = null;
 String _s = null;
 _l = l;
 _d = new Date(_l);
 _sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 _s = _sdf.format(_d);
 return _s;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 文本的倒序输出

back

文件 before:

Hello
World
1
2

要求输出文件 after:

World
Hello
1
2
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.ListIterator;
public class ReverseOrder extends ArrayList {
 public static String read(String fileName) throws IOException {
 StringBuffer sb = new StringBuffer();
 LinkedList lines = new LinkedList();
 BufferedReader in = new BufferedReader(new FileReader(fileName));
 String s;
 while ((s = in.readLine()) != null)
 lines.add(s);
 in.close();
 ListIterator it = lines.listIterator(lines.size());
 while (it.hasPrevious()) {
 sb.append(it.previous());
 sb.append("n");
}
return sb.toString();
}
public static void write(String fileName, String text) throws IOException { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(
fileName)));
out.print(text);
out.close();
}
public ReverseOrder(String fileName) throws IOException { super(Arrays.asList(read(fileName).split("n")));
}
public void write(String fileName) throws IOException {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter( fileName)));
for (int i = 0; i < size(); i++)
out.println(get(i));
out.close();
}
public static void main(String[] args) throws Exception { String fileName = "e:\1124\before.txt";
ReverseOrder text = new ReverseOrder(fileName);
text.write("e:\1124\after.txt");
}
/*
* 最后会多一个空行,手工删除一下
*/
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

# 判断一个数字是奇数还是偶数

back

判断一个数是否是奇数:

public static Boolean isOdd(int i) {
 return (i&1) != 0;
}
1
2
3

判断一个数是否是偶数

public static Boolean isEven(int i) {
 return (i&1) = 0;
}
//位运算符说明在 java 文件夹里面
1
2
3
4

# 用Hibernate实现分页

back

public List queryByStatus(int status, int currentPage, int lineSize)
throws Exception {
 List all = null;
 String hql = "FROM Question AS q WHERE q.status=? ORDER BY q.questiontime desc";
 Query q = super.getSession().createQuery(hql);
 q.setInteger(0, status);
 q.setFirstResult((currentPage - 1) * lineSize);
 q.setMaxResults(lineSize);
 all = q.list();
 return all;
}
1
2
3
4
5
6
7
8
9
10
11

# 35选7彩票程序

back

public class caipiao
{
 static void generate()
 {
 int a[]=new int[7];
 int i,m,j;
 fan:for (j=0;j <7;j++){
 //外循环实现随机生成每组 7 个数
 a[j]=(int)(Math.random()*35+1);
 m=a[j];
 if(j>=1){
 for (i=0;i <j;i++)//内循环实现无重复
 if(a[i]==m){
 j--;
 continue fan;
 }
 }
 if(a[j] <10)
 System.out.print("0"+a[j]+" "); else
 System.out.print(a[j]+" ");
 }
 }

 public static void main (String args[]){
    int n=Integer.parseint(args[0]);
    System.out.println("中国福利彩票 35 选 7");
    for (int i=0;i <n;i++){
    //循环调用方法实现输出 n 组数
    generate();
    System.out.println();
 }
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

# 获取GMT8时间

back

/**
* Description: 获取 GMT8 时间
* @return 将当前时间转换为 GMT8 时区后的 Date */
public static Date getGMT8Time(){
 Date gmt8 = null;
 try {
 Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"),Locale.CHINESE);
 Calendar day = Calendar.getInstance();
 day.set(Calendar.YEAR, cal.get(Calendar.YEAR));
 day.set(Calendar.MONTH, cal.get(Calendar.MONTH));
 day.set(Calendar.DATE, cal.get(Calendar.DATE));
 day.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY));
 day.set(Calendar.MINUTE, cal.get(Calendar.MINUTE));
 day.set(Calendar.SECOND, cal.get(Calendar.SECOND));
 gmt8 = day.getTime();
 }
 catch (Exception e) {
 System.out.println("获取 GMT8 时间 getGMT8Time() error !");
 e.printStackTrace();
 gmt8 = null;
 }
 return gmt8;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 中文乱码转换

back

public String china(String args)
{
 String s=null;
 String s=new String(args.getBytes("ISO-8859-1"),"gb2312");
 return s;
}
1
2
3
4
5
6

# 小标签

back

import java.io.IOException;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import com.formcontent.show.ShowFormTypeOperateDb;
import com.forum.hibernatePrj.Space;
public class OutPrintForumType extends TagSupport{
 public int doStartTag() throws JspException
 {
 String printStr="";
 ShowFormTypeOperateDb showtype=new ShowFormTypeOperateDb();
 List list=showtype.getForumType();
 if(list!=null&&list.size()>0)
 {
 for (int i=0;i <list.size();i++)
 {
 Space space=(Space)list.get(i);
 if(space!=null)
 {
 printStr+=" <tr> <td>"+" <div align='left' class='TypeCss'>"+
 space.getSpaceName()+" "+space.getSpaceDescription()+" <br/>目前登陆总人数:"+i+" 人访问数:"+i+"人 </div> </td> </tr>"
 +" <tr> <td> </td> </tr>";
 }
 }
 }
 try {
 pageContext.getOut().write(printStr);
 }
 catch (IOException e) {
 e.printStackTrace();
 }
 return super.doStartTag();
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

# Big5字与Unicode的互换

back

/**
* Big5 字与 Unicode 的互换
* 转换后的正常字型
*/
import java.io.*;
public class MyUtil{
 public static String big5ToUnicode(String s){
 try{
 return new String(s.getBytes("ISO8859_1"), "Big5");
 }
 catch (UnsupportedEncodingException uee){
 return s;
 }
 }
 public static String UnicodeTobig5(String s){
 try{
 return new String(s.getBytes("Big5"), "ISO8859_1");
 }
 catch (UnsupportedEncodingException uee){
 return s;
 }
 }
 public static String toHexString(String s){
 String str="";
 for (int i=0; i<s.length(); i++){
 int ch=(int)s.charAt(i);
 String s4="0000"+Integer.toHexString(ch);
 str=str+s4.substring(s4.length()-4)+" ";
 }
 return str;
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

# 取得服务器当前的各种具体时间

back

/**
* 取得服务器当前的各种具体时间
* 回车:日期时间
*/
import java.util.*;
public class GetNowDate{
 Calendar calendar = null;
 public GetNowDate(){
 calendar = Calendar.getInstance();
 calendar.setTime(new Date());
 }
 public int getYear(){
 return calendar.get(Calendar.YEAR);
 }
 public int getMonth(){
 return 1 + calendar.get(Calendar.MONTH);
 }
 public int getDay(){
 return calendar.get(Calendar.DAY_OF_MONTH);
 }
 public int getHour(){
 return calendar.get(Calendar.HOUR_OF_DAY);
 }
 public int getMinute(){
 return calendar.get(Calendar.MINUTE);
 }
 public int getSecond(){
 return calendar.get(Calendar.SECOND);
 }
 public String getDate(){
 return getMonth()+"/"+getDay()+"/"+getYear();
 }
 public String getTime(){
 return getHour()+":"+getMinute()+":"+getSecond();
 }
 public String getDate2(){
 String yyyy="0000", mm="00", dd="00";
 cy = yyyy + getYear();
 mm = mm + getMonth();
 dd = dd + getDay();
 cy = yyyy.substring(yyyy.length()-4);
 mm = mm.substring(mm.length()-2);
 dd = dd.substring(dd.length()-2);
 return yyyy + "/" + mm + "/" + dd;
 }
 public String getTime2(){
 String hh="00", mm="00", ss="00";
 ah = hh + getHour();
 mm = mm + getMinute();
 ss = ss + getSecond();
 hh = hh.substring(hh.length()-2, hh.length());
 mm = mm.substring(mm.length()-2, mm.length());
 ss = ss.substring(ss.length()-2, ss.length());
 return hh + ":" + mm + ":" + ss;
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

# 用半角的特殊符号代替全角的特殊符号

back

/**
* 用半角的特殊符号代替全角的特殊符号
* 防止特殊字符在传输参数时出现错误
*/
public class ReplaceStrE{
 public static String rightToError(String ss){
 String strs;
 String strs1;
 String strs2;
 String strs3;
 String strs4;
 try{
 strs = ss.replace('#','#');
 }
 catch(Exception ex){
 return ss;
 }
 try{
 strs1 = strs.replace('"','"');
 }
 catch(Exception ex){
 return strs;
 }
 try{
 strs2 = strs1.replace(' ','&');
 }
 catch(Exception ex){
 return strs1;
 }
 try{
 strs3 = strs2.replace('+','+');
 }
 catch(Exception ex){
 return strs2;
 }
 try{
 strs4 = strs3.replace(''',''');
}
catch(Exception ex){
return ss;
}
return strs4;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

# 数组和数组之间的转换代码

back

import java.lang.reflect.Array;
import java.util.Date;
public class TestCast {
 /** 
* 将数组 array 转换成 clss 代表的类型后返回
* @param array 需要转换的数组
* @param clss 要转换成的类型
* @return 转换后的数组
*/
 public static Object cast(Object array,Class clss){
 if(null==clss)
 throw new IllegalArgumentException("argument clss cannot be null");
 if(null==array)
 throw new IllegalArgumentException("argument array cannot be null");
 if(false==array.getClass().isArray())
 throw new IllegalArgumentException("argument array must be array");
 Object[] src=(Object[])array;
 Object[] dest=(Object[])Array.newInstance(clss, src.length);
 System.arraycopy(src, 0, dest, 0, src.length);
 return dest;
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# 从资源文件里读取值的类

back

从资源文件里读取值的类,文件后缀不一定要.Properties,只要里面内容如:url=www.cnsec.net可通过 key(url)取得值-www.cnsec.net,简单、强大

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
/**
* ReadProperties.java
* Description: 读取操作属性配置文件
* @author li.b
* @version 2.0
* Jun 26, 2008
*/
public class ReadProperties {
 /**
* Description: 获取属性配置文件
* @param path 资源文件路径
* @return Properties Object
* @throws FileNotFoundException
* @throws IOException
*/
 public static Properties getProperties(String path) throws FileNotFoundException, IOException{
 Properties props = null;
 File file = new File(path);
 if(file.exists() && file.isFile()){
 props = new Properties();
 props.load(new FileInputStream(file));
 } else{
 System.out.println(file.toString() + "不存在!");
 }
 return props;
 }
 /**
* Description: 从属性文件获取值
* @param props Properties Object
* @param key
* @return 通过 key 匹配到的 value
*/
 public static String getValue(Properties props,String key,String encod){
 String result = "";
 String en = "";
 String localEN = System.getProperty("file.encoding");
 if(encod !=null && !encod.equals("") ){
 en = encod;
 } else{
 en = localEN;
 }
 try {
 key = new String(key.getBytes(en),"ISO-8859-1");
 result = props.getProperty(key);
 if(!result.equals("")){
 result = new String(result.getBytes("ISO-8859-1"),en);
 }
 }
 catch (Exception e) {
 }
 finally{
 if(result == null)result = "";
 return result;
 }
 }
 public static String getValue(Properties props,String key){
 return getValue(props, key, "");
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

# 一个随机类

back

/*
* @author www.wuliaokankan.cn
* Copyright (C) 2007 
* 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
* @return the random double value
*/
 public static double getRandomdouble( double min, double max )
 {
 // include min, exclude max
 double result = min + ( Math.random() * ( max - min ) );
 return result;
 }
 /**
*
* @return a random char with the range ASCII 33(!) to ASCII 126(~) */
 public static char getRandomchar()
 {
 / from ASCII code 33 to ASCII code 126 int firstchar = 33;
 // "!"
 int lastchar = 126;
 // "~"
 char result = ( char ) ( getRandomint( firstchar, lastchar + 1 ) );
 return result;
 }
 /**
*
* @return a random rgb color */
 public static RGB getRandomRGB()
 {
 int red = getRandomint(0,256);
 int green = getRandomint(0,256);
 int blue = getRandomint(0,256);
 return new RGB( red, green, blue );
 }
 /**
*
* @return a random char with the range [0-9],[a-z],[A-Z] */
 public static char getRandomNormalchar()
 {
 // include 0-9,a-z,A-Z
 int number = getRandomint( 0, 62 );
 int zerochar = 48;
 int ninechar = 57;
 int achar = 97;
 int zchar = 122;
 int Achar = 65;
 int Zchar = 90;
 char result;
 if( number < 10 )
 {
 result = ( char ) ( getRandomint( zerochar, ninechar + 1 ) );
 return result;
 } else if( number >= 10 && number < 36 )
 {
 result = ( char ) ( getRandomint( Achar, Zchar + 1 ) );
 return result;
 } else if( number >= 36 && number < 62 )
 {
 result = ( char ) ( getRandomint( achar, zchar + 1 ) );
 return result;
 } else
 {
 return 0;
 }
 }
 /**
*
* @param length the length of the String
* @return a String filled with random char */
 public static String getRandomString( int length )
 {
 / include ASCII code from 33 to 126 StringBuffer result = new StringBuffer();
 for ( int i = 0; i < length; i++ )
 {
 result.append( getRandomchar() );
 }
 return result.toString();
 }
 /**
*
* @param length the length of the String
* @return a String filled with normal random char */
 public static String getRandomNormalString( int length )
 {
 // include 0-9,a-z,A-Z
 StringBuffer result = new StringBuffer();
 for ( int i = 0; i < length; i++)
 {
 result.append( getRandomNormalchar() );
 }
 return result.toString();
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158

# 计算传入值是否星期六

back

/**
* 计算传入值是否星期六
* 回车:true or false
*/
import java.util.*;
public class Week6 {
 public Boolean checkWeek6(String str){
 Boolean flag=false;
 int week6=0;
 str.replace('/','-');
 Calendar cal=Calendar.getInstance();
 cal.setTime(java.sql.Date.valueOf(str.substring(0,10)));
 week6=cal.get(Calendar.DAY_OF_WEEK);
 if(week6==7){
 flag=true;
 }
 return flag;
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 转换文件大小

back

import java.text.DecimalFormat;
import java.util.Hashtable;
/**
* 文件大小单位转换
* @author Administrator
*/
public class UnitsConversion extends DecimalFormat {
 private static final long serialVersionUID = 3168068393840262910L;
 /**
* 存放有效单位的数组
*/
 private static Hashtable<String, String> validUnits = new Hashtable<String, String>();
 /**
* 限制文件大小上限为 1G
*/
 private static int GB_MAX_SIZE = 1;
 /**
* 最大的 MB 值
*/
 private static int MB_MAX_SIZE = GB_MAX_SIZE * 1024;
 /**
* 最大的 KB 值
*/
 private static int KB_MAX_SIZE = MB_MAX_SIZE * 1024;
 /**
* 最大的 Bytes 值
*/
 private static int BYTES_MAX_SIZE = KB_MAX_SIZE * 1024;
 /**
* 数字部分的值
*/
 private double numPart;
 /**
* 原始的单位字符串
*/
 private String originalUnit;
 /**
* 标准的单位字符串
*/
 private String unit;
 /**
* 转换后的结果
*/
 private String result;
 / 添加所有有效单位 static {
 validUnits.put("字节", "Bytes");
 validUnits.put("bytes", "Bytes");
 validUnits.put("byte", "Bytes");
 validUnits.put("kb", "KB");
 validUnits.put("k", "KB");
 validUnits.put("兆", "MB");
 validUnits.put("mb", "MB");
 validUnits.put("m", "MB");
 validUnits.put("gb", "GB");
 validUnits.put("g", "GB");
 }
 /**
* 构造方法:指定了数字格式,初始所有属性为 NULL
*/
 public UnitsConversion() {
 super("########.##");
 numPart = null;
 result = null;
 unit = null;
 originalUnit = null;
 }
 /**
* 根据单位、数字大小按照常用的转换原则进行转换
* @param input
* @return 成功转换后的结果是非空字符串;若失败了,结果为空字符串
*/
 public String defaultConversion(String input) {
 analyzeString(input);
 if (result != null) {
 return result;
 }
 // 单位 Bytes
 if (unit.equals("Bytes")) {
 int numPart2int = numPart.intValue();
 / 输入大小与 1G 相差 0.5M 之内,返回 1GB
 if ((BYTES_MAX_SIZE - numPart2int) < (1024 * 1024) / 2) {
 return "1 GB";
 }
 // (0,1KB)
 if (numPart2int < 1024) {
 return numPart2int + " Bytes";
 }
 // [1KB,1023KB]
 if (numPart2int >= 1024 && numPart2int <= (1024 - 1) * 1024) {
 return format(numPart / 1024) + " KB";
 }
 // (1023KB,1GB)
 if (numPart2int > (1024 - 1) * 1024 && numPart2int < BYTES_MAX_SIZE) {
 return format(numPart / (1024 * 1024)) + " MB";
 } else
 result = "";
 return result;
 }
 if (unit.equals("KB")) {
 return "还没实现....";
 }
 if (unit.equals("MB")) {
 return "还没实现....";
 }
 if (unit.equals("GB")) {
 return "还没实现....";
 }
 result = "";
 return result;
 }
 /** * 把字符串的数字部分与单位分离,并对数字、单位的有效性进行检验, 若有非法状况,把结果赋值为 "" ,将其返回给用户 * * @param input
*/
 public void analyzeString(String input) {
 / 初步检验输入的字符串
 if (input == null || input.trim().length() < 2) {
 System.out.println("输入的字符串有误");
 result = "";
 return;
 }
 input = input.replaceAll(" ", "");
 int firstIndexOfUnit;
 // 单位的起始位置
 String strOfNum;
 // 数字部分的字符串
 / 从尾部开始遍历字符串
 for (int i = input.length() - 1; i >= 0; i--) {
 if (Character.isDigit(input.charAt(i))) {
 firstIndexOfUnit = i + 1;
 originalUnit = input.substring(firstIndexOfUnit,
 input.length()).toLowerCase();
 if (!isValidUnit(originalUnit)) {
 System.out.println("无效单位。");
 result = "";
 return;
 }
 unit = validUnits.get(originalUnit);
 strOfNum = input.substring(0, firstIndexOfUnit);
 numPart = double.parsedouble(strOfNum);
 if (!isValidNum(numPart, unit)) {
 System.out.println("文件大小非法");
 result = "";
 return;
 }
 if (numPart == 0) {
 result = "0 Bytes";
 return;
 }
 break;
 }
 }
 if (unit == null || numPart == null) {
 System.out.println("输入的字符串有误");
 result = "";
 return;
 }
 }
 /**
* 文件大小越界检查
* 
* @param num
* @param unit
* @return 在 1G 范围内(包括 1G),返回 true;否则返回 false */
 public Boolean isValidNum(double num, String unit) {
 if (num == null || num < 0 || num > BYTES_MAX_SIZE) {
 return false;
 }
 if (unit.equals("KB") && num > KB_MAX_SIZE) {
 return false;
 }
 if (unit.equals("MB") && num > MB_MAX_SIZE) {
 return false;
 }
 if (unit.equals("GB") && num > GB_MAX_SIZE) {
 return false;
 }
 return true;
 }
 /**
* 检查原始单位 originalUnit 是否有效
* 
* @param originalUnit
* @return 若 originalUnit 为空,那么会给他赋默认值 bytes ,并返回 true;<br>
* 若 originalUnit 是有效单位集合中之一,返回 true。
*/
 public Boolean isValidUnit(String originalUnit) {
 if (originalUnit == null || originalUnit.trim().length() < 1) {
 originalUnit = "bytes";
 return true;
 }
 for (String validUnit : validUnits.keySet()) {
 if (validUnit.equalsIgnoreCase(originalUnit)) {
 return true;
 }
 }
 return false;
 }
 //测试
 public static void main(String[] args) {
 System.out.println("-------------");
 for (int i = 1020 * 1024; i <= 1024 * 1111; i += 9) {
 String input = i + " ";
 System.out.println(input + " ---> "
 + new UnitsConversion().defaultConversion(input));
 }
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206

# Java日期格式化及其使用例子

back

  • ①. SimpleDateFormat 担当重任,怎样格式化都行
import java.util.Date;
import java.text.SimpleDateFormat;
public class Demo
{
 public static void main(String[] args)
 {
 Date now=new Date();
 SimpleDateFormat f=newSimpleDateFormat("今天是"+"yyyy 年 MM 月 dd 日 E kk 点 mm 分");
 System.out.println(f.format(now));
 f=new SimpleDateFormat("a hh 点 mm 分 ss 秒");
 System.out.println(f.format(now));
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
  • ②. 从字符串到日期类型的转换:
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.text.*;
publicclass Demo
{
 public static void main(String[] args)
 {
 String strDate="2005 年 04 月 22 日";
 //注意:SimpleDateFormat 构造函数的样式与 strDate 的样式必须相符
 SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy 年 MM 月 dd 日");
 //必须捕获异常
 try
 {
 Date date=simpleDateFormat.parse(strDate);
 System.out.println(date);
 }
 catch(ParseException px)
 {
 px.printStackTrace();
 }
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  • ③. 将毫秒数换转成日期类型
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.text.*;
public class Demo
{
 public static void main(String[] args)
 {
 long now=System.currentTimeMillis();
 System.out.println("毫秒数:"+now);
 Date dNow=new Date(now);
 System.out.println("日期类型:"+dNow);
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  • ④. 获取系统时期和时间,转换成 SQL 格式后更新到数据库
java.util.Date d=new java.util.Date();
//获取当前系统的时间
//格式化日期
new java.text.SimpleDateFormat s= new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = s.format(d);
//转为字符串
// 使用 RS 更新数据库,仍然要用 rs.updateString,而不是 rs.updateDade。 rs.updateString("regtime",dateStr);
//regtime 字段为 datetime 类型的
1
2
3
4
5
6
7
8
  • ⑤. 按本地时区输出当前日期
Date myDate = new Date();
System.out.println(myDate.toLocaleString());
1
2

输出结果为:
2003-5-30

  • ⑥. 如何格式化小数
DecimalFormat df = new DecimalFormat(",###.00");
double aNumber = 33665448856.6568975;
String result = df.format(aNumber);
Sytem. out.println(result);
1
2
3
4

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

其他:获取毫秒时间 System.currentTimeMillis();

  • ⑦. 在数据库里的日期只以年-月-日的方式输出
// 定义日期格式:
SimpleDateFormat sdf = new SimpleDateFormat(yy-MM-dd);
// sql 语句为:

String sqlStr = "select bookDate from roomBook where bookDate between '2007-4-10' and '2007-4-25'";
// 输出:
System.out.println(df.format(rs.getDate("bookDate")));
1
2
3
4
5
6
7

# java几个常用方法

  • 字符串
    • ①. 获取字符串的长度length()
    • ②. 判断字符串的前缀或后缀与已知字符串是否相同前缀 startsWith(String s),后缀 endsWith(String s)
    • ③. 比较两个字符串 equals(String s)
    • ④. 把字符串转化为相应的数值 int 型 Integer.parseInt(字符串) long 型 Long.parseLong(字符串),float 型 Folat.valueOf(字符串).floatValue() double 型 Double.valueOf(字符串).doubleValue()
    • ⑤. 将数值转化为字符串valueOf(数值)
    • ⑥. 字符串检索:indexOf(Srting s) 从头开始检索,indexOf(String s ,int startpoint) 从 startpoint 处开始检索如果没有检索到,将返回-1
    • ⑦. 得到字符串的子字符串:substring(int startpoint) 从 startpoint 处开始获取 substring(int start,int end) 从 start 到 end 中间的字符
    • ⑧. 替换字符串中的字符,去掉字符串前后空格:replace(char old,char new) 用 new 替换 oldtrim()
    • ⑨. 分析字符串:StringTokenizer(String s) 构造一个分析器,使用默认分隔字符(空格,换行,回车,Tab,进纸符)
      • StringTokenizer(String s,String delim) delim 是自己定义的分隔符
      • nextToken() 逐个获取字符串中的语言符号,
      • boolean hasMoreTokens() 只要字符串还有语言符号将返回 true,否则返回 false
      • countTokens() 得到一共有多少个语言符号

# Java中的鼠标和键盘事件

①. 使用 MouseListener 借口处理鼠标事件

鼠标事件有 5 种:按下鼠标键,释放鼠标键,点击鼠标键,鼠标进入和鼠标退出,鼠标事件类型是 MouseEvent,主要方法有:

  • getX(),getY() 获取鼠标位置
  • getModifiers() 获取鼠标左键或者右键
  • getClickCount() 获取鼠标被点击的次数
  • getSource() 获取鼠标发生的事件源
    • 事件源获得监视器的方法是 addMouseListener(),
    • 移去监视器的方法是 removeMouseListener() 处理事件源发生的时间的事件的接口是 MouseListener 接口中有如下的方法 mousePressed(MouseEvent) 负责处理鼠标按下事件
    • mouseReleased(MouseEvent) 负责处理鼠标释放事件
  • mouseEntered(MouseEvent) 负责处理鼠标进入容器事件
  • mouseExited(MouseEvent) 负责处理鼠标离开事件
  • mouseClicked(MouseEvent) 负责处理点击事件

②. 使用 MouseMotionListener 接口处理鼠标事件

事件源发生的鼠标事件有 2 种:拖动鼠标和鼠标移动

  • 鼠标事件的类型是 MouseEvent
  • 事件源获得监视器的方法是 addMouseMotionListener()
  • 处理事件源发生的事件的接口是 MouseMotionListener 接口中有如下的方法
    • mouseDragged() 负责处理鼠标拖动事件
    • mouseMoved() 负责处理鼠标移动事件

③. 控制鼠标的指针形状

setCursor(Cursor.getPreddfinedCursor(Cursor.鼠标形状定义)) 鼠标形状定义见(书 P 210)

④. 键盘事件

键盘事件源使用 addKeyListener 方法获得监视器,键盘事件的接口是 KeyListener 接口中有 3 个方法

  • public void keyPressed(KeyEvent e) 按下键盘按键
  • public void keyReleased(KeyEvent e) 释放键盘按键
  • public void keyTypde(KeyEvent e) 按下又释放键盘按键

# 判断字符是否属于中文

public class IsChineseOrEnglish {
 // GENERAL_PUNCTUATION 判断中文的“号
 // CJK_SYMBOLS_AND_PUNCTUATION 判断中文的。号
 // HALFWIDTH_AND_FULLWIDTH_FORMS 判断中文的,号
 public static Boolean isChinese(char c) {
 Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
 if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
 || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
 || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
 || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
 || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
 || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS){
 return true;
 }
 return false;
 }
 public static void isChinese(String strName) {
 char[] ch = strName.toCharArray();
 for (int i = 0; i < ch.length; i++) {
 char c = ch[i];
 if(isChinese(c)==true){
 System.out.println(isChinese(c));
 return;
 } else{
 System.out.println(isChinese(c));
 return ;
 }
 }
 }
 public static void main(String[] args){
 isChinese("zhongguo");
 isChinese("中国");
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

# 去掉字符串中重复的子字符串

/**
* 去掉字符串中重复的子字符串
* @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);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 将指定 byte 数组以 16 进制的形式打印到控制台

/**
* 将指定 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("");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 获得任意一个整数的阶乘,递归

/**
* 获得任意一个整数的阶乘,递归
* @param n
* @return n!
*/
public static int factorial(int n)
{
 if (n == 1)
 {
 return 1;
 }
 return n * factorial(n - 1);
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 拷贝一个目录或者文件到指定路径下

/**
* 拷贝一个目录或者文件到指定路径下
* @param source
* @param target
*/
public static void copy(File source, File target)
{
 File tarpath = new File(target, source.getName());
 if (source.isDirectory())
 {
 tarpath.mkdir();
 File[] dir = source.listFiles();
 for (int i = 0; i < dir.length; i++) {
 copy(dir[i], tarpath);
 }
 } else
 {
 try
 {
 InputStream is = new FileInputStream(source);
 OutputStream os = new FileOutputStream(tarpath);
 byte[] buf = new byte[1024];
 int len = 0;
 while ((len = is.read(buf)) != -1)
 {
 os.write(buf, 0, len);
 }
 is.close();
 os.close();
 }
 catch (FileNotFoundException e)
 {
 e.printStackTrace();
 }
 catch (IOException e)
 {
 e.printStackTrace();
 }
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

# 简单的 txt 转换 xml

package cn.wuliaokankan;
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);
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

# 字母排序(A-Z)(先大写,后小写)

import java.util.Arrays;
import java.util.Comparator;
public class SortTest
{
 public static void main(String args[])
 {
 char[] chs = {'f', 'F', 'K', 'A', 'a', 'j', 'z'};
 chs = sortChars(chs, false);
 for (char c: chs)
 {
 System.out.println(c);
 }
 }
 /**
* 对给定的字符数组进行字典排序
* @param chs 目标字符数组
* @param upperFisrt 大写字母是否在前
* @return 排序后的字符数组
*/
 public static char[] sortChars(char[] chs, final Boolean upperFisrt)
 {
 Character[] srcArray = new Character[chs.length];
 char[] retArray = new char[chs.length];
 int index = 0;
 for (char ch: chs)
 {
 srcArray[index++] = ch;
 }
 Arrays.sort(srcArray, new Comparator<Character>()
 {
 public int compare(Character c1, Character c2)
 {
 char ch1 = Character.toUpperCase(c1);
 char ch2 = Character.toUpperCase(c2);
 if(ch1 == ch2)
 {
 int tempRet = c1.charValue() - c2.charValue();
 return upperFisrt? tempRet: -tempRet;
 } else
 {
 return ch1 - ch2;
 }
 }
 }
 );
 index = 0;
 for (char ch: srcArray)
 {
 retArray[index++] = ch;
 }
 return retArray;
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

# 列出某文件夹及其子文件夹下面的文件,并可根据扩展名过滤

/**
* 列出某文件夹及其子文件夹下面的文件,并可根据扩展名过滤
* @param path
*/
public static void list(File path)
{
 if (!path.exists())
 {
 System.out.println("文件名称不存在!");
 } else
 {
 if (path.isFile())
 {
 if (path.getName().toLowerCase().endsWith(".pdf")
 || path.getName().toLowerCase().endsWith(".doc")
 || path.getName().toLowerCase().endsWith(".html")
 || path.getName().toLowerCase().endsWith(".htm"))
 {
 System.out.println(path);
 System.out.println(path.getName());
 }
 } else
 {
 File[] files = path.listFiles();
 for (int i = 0; i < files.length; i++)
 {
 list(files[i]);
 }
 }
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

# 字符串匹配的算法

public String getMaxMatch(String a,String b) {
 StringBuffer tmp = new StringBuffer();
 String maxString = "";
 int max = 0;
 int len = 0;
 char[] aArray = a.toCharArray();
 char[] bArray = b.toCharArray();
 int posA = 0;
 int posB = 0;
 while(posA<aArray.length-max) {
 posB = 0;
 while(posB<(bArray.length-max)) {
 if(aArray[posA]==bArray[posB]) {
 len = 1;
 tmp = new StringBuffer();
 tmp.append(aArray[posA]);
 while((posA+len<aArray.length)&&(posB+len<bArray.length)&&(aArray[posA+len]==bArray[posB+len]))
 {
 tmp.append(aArray[posA+len]);
 len++;
 }
 if(len>max) {
 max = len;
 maxString = tmp.toString();
 }
 }
 posB++;
 }
 posA++;
 }
 return maxString;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32