久久精品在线,亚洲成人二区,香蕉成人在线http://www.aygfsteel.com/kyleYang/category/42721.html孩兒立志出鄉關,學不成名誓不還。 風華正茂乾坤地,人生無處不青山。 光陰如同流水去,珍惜時光最寶貴。 鵬程萬里靠自己,飛黃騰達青少年。 zh-cnWed, 11 Aug 2010 02:53:28 GMTWed, 11 Aug 2010 02:53:28 GMT60解析Java對象的equals()和hashCode()的使用http://www.aygfsteel.com/kyleYang/archive/2010/08/11/328469.html飛熊飛熊Wed, 11 Aug 2010 00:44:00 GMThttp://www.aygfsteel.com/kyleYang/archive/2010/08/11/328469.htmlhttp://www.aygfsteel.com/kyleYang/comments/328469.htmlhttp://www.aygfsteel.com/kyleYang/archive/2010/08/11/328469.html#Feedback0http://www.aygfsteel.com/kyleYang/comments/commentRss/328469.htmlhttp://www.aygfsteel.com/kyleYang/services/trackbacks/328469.html 前言

在Java語言中,equals()和hashCode()兩個函數的使用是緊密配合的,你要是自己設計其中一個,就要設計另外一個。在多數情況 下,這兩個函數是不用考慮的,直接使用它們的默認設計就可以了。但是在一些情況下,這兩個函數最好是自己設計,才能確保整個程序的正常運行。最常見的是當 一個對象被加入收集對象(collection object)時,這兩個函數必須自己設計。更細化的定義是:如果你想將一個對象A放入另一個收集對象B里,或者使用這個對象A為查找一個元對象在收集對 象B里位置的鑰匙,并支持是否容納,刪除收集對象B里的元對象這樣的操作,那么,equals()和hashCode()函數必須開發者自己定義。其他情 況下,這兩個函數是不需要定義的。

equals():

它是用于進行兩個對象的比較的,是對象內容的比較,當然也能用于進行對象參閱值的比較。什么是對象參閱值的比較?就是兩個參閱變量的值得比較,我們 都知道參閱變量的值其實就是一個數字,這個數字可以看成是鑒別不同對象的代號。兩個對象參閱值的比較,就是兩個數字的比較,兩個代號的比較。這種比較是默 認的對象比較方式,在Object這個對象中,這種方式就已經設計好了。所以你也不用自己來重寫,浪費不必要的時間。

對象內容的比較才是設計equals()的真正目的,Java語言對equals()的要求如下,這些要求是必須遵循的。否則,你就不該浪費時間:
  • 對稱性:如果x.equals(y)返回是“true”,那么y.equals(x)也應該返回是“true”。
  • 反射性:x.equals(x)必須返回是“true”。
  • 類推性:如果x.equals(y)返回是“true”,而且y.equals(z)返回是“true”,那么z.equals(x)也應該返回是“true”。
  • 還有一致性:如果x.equals(y)返回是“true”,只要x和y內容一直不變,不管你重復x.equals(y)多少次,返回都是“true”。
  • 任何情況下,x.equals(null),永遠返回是“false”;x.equals(和x不同類型的對象)永遠返回是“false”。
hashCode():
這 個函數返回的就是一個用來進行赫希操作的整型代號,請不要把這個代號和前面所說的參閱變量所代表的代號弄混了。后者不僅僅是個代號還具有在內存中才查找對 象的位置的功能。hashCode()所返回的值是用來分類對象在一些特定的收集對象中的位置。這些對象是HashMap, Hashtable, HashSet,等等。這個函數和上面的equals()函數必須自己設計,用來協助HashMap, Hashtable, HashSet,等等對自己所收集的大量對象進行搜尋和定位。

這些收集對象究竟如何工作的,想象每個元對象hashCode是一個箱子的 編碼,按照編碼,每個元對象就是根據hashCode()提供的代號歸入相應的箱子里。所有的箱子加起來就是一個HashSet,HashMap,或 Hashtable對象,我們需要尋找一個元對象時,先看它的代碼,就是hashCode()返回的整型值,這樣我們找到它所在的箱子,然后在箱子里,每 個元對象都拿出來一個個和我們要找的對象進行對比,如果兩個對象的內容相等,我們的搜尋也就結束。這種操作需要兩個重要的信息,一是對象的 hashCode(),還有一個是對象內容對比的結果。

hashCode()的返回值和equals()的關系如下:
  • 如果x.equals(y)返回“true”,那么x和y的hashCode()必須相等。
  • 如果x.equals(y)返回“false”,那么x和y的hashCode()有可能相等,也有可能不等。


為什么這兩個規則是這樣的,原因其實很簡單,拿HashSet來說吧,HashSet可以擁有一個或更多的箱子,在同一個箱子中可以有一個 或更多的獨特元對象(HashSet所容納的必須是獨特的元對象)。這個例子說明一個元對象可以和其他不同的元對象擁有相同的hashCode。但是一個 元對象只能和擁有同樣內容的元對象相等。所以這兩個規則必須成立。

設計這兩個函數所要注意到的:
如果你設計的對象類型并不使用于收集性對象,那么沒有必要自己再設計這兩個函數的處理方式。這是正確的面向對象設計方法,任何用戶一時用不到的功能,就先不要設計,以免給日后功能擴展帶來麻煩。

如果你在設計時想別出心裁,不遵守以上的兩套規則,那么勸你還是不要做這樣想入非非的事。我還沒有遇到過哪一個開發者和我說設計這兩個函數要違背前面說的兩個規則,我碰到這些違反規則的情況時,都是作為設計錯誤處理。

當一個對象類型作為收集型對象的元對象時,這個對象應該擁有自己處理equals(),和/或處理hashCode()的設計,而且要遵守前面所說 的兩種原則。equals()先要查null和是否是同一類型。查同一類型是為了避免出現ClassCastException這樣的異常給丟出來。查 null是為了避免出現NullPointerException這樣的異常給丟出來。

如果你的對象里面容納的數據過多,那么這兩個函數 equals()和hashCode()將會變得效率低。如果對象中擁有無法serialized的數據,equals()有可能在操作中出現錯誤。想象 一個對象x,它的一個整型數據是transient型(不能被serialize成二進制數據流)。然而equals()和hashCode()都有依靠 這個整型數據,那么,這個對象在serialization之前和之后,是否一樣?答案是不一樣。因為serialization之前的整型數據是有效的 數據,在serialization之后,這個整型數據的值并沒有存儲下來,再重新由二進制數據流轉換成對象后,兩者(對象在serialization 之前和之后)的狀態已經不同了。這也是要注意的。

知道以上這些能夠幫助你:
1. 進行更好的設計和開發。
2. 進行更好的測試案例開發。
3. 在面試過程中讓面試者對你的學識淵博感到滿意。

飛熊 2010-08-11 08:44 發表評論
]]>
COOKIEhttp://www.aygfsteel.com/kyleYang/archive/2010/02/08/312346.html飛熊飛熊Mon, 08 Feb 2010 09:33:00 GMThttp://www.aygfsteel.com/kyleYang/archive/2010/02/08/312346.htmlhttp://www.aygfsteel.com/kyleYang/comments/312346.htmlhttp://www.aygfsteel.com/kyleYang/archive/2010/02/08/312346.html#Feedback2http://www.aygfsteel.com/kyleYang/comments/commentRss/312346.htmlhttp://www.aygfsteel.com/kyleYang/services/trackbacks/312346.html1.COOKIE
HTTP COOKIE實質是服務端與在客戶端之間傳送的普通HTTP頭,可保存也可不保存在客戶的硬盤上.如果保存,每一個文件大小不超過4K的文本文件.多個COOKIE可保存到同一個文件中. 如果從編程角度來看,在JSP中COOKIE就是JAVA提供的一個類.常用的方法如下所表示,因為客戶端可能不接受COOKIE,所以建議不用它,改用SESSION等其他方式。

public class cookie
{
public String getDomain() //返回該COOKIE的有效域
public int getMaxAge() //返回該COOKIE的有效期,單位為秒
public String getName() //返回該COOKIE的名稱
public String getPath() //返回該COOKIE的有效路徑
public boolean getSecure() //返回該COOKIE的安全設置
public String getValue() //返回該COOKIE的值
public void setDomain(java.lang.String pattern) //設置該COOKIE的有效域
public void setMaxAge(int expiry) //設置該COOKIE的有效期,單位為秒
public void setPath(java.lang.String uri) //設置該COOKIE的有效路徑
public void setSecure(boolean flag) //設置該COOKIE的安全設置
public void setValue(java.lang.String newValue) //設置該COOKIE的值
}
一個COOKIE包含以下五部分:
NAME/VALUE對,設置該COOKIE的名字及它保存的值
COOKIE通常和服務器相關,如果將域設為JAVA.SUN.COM,那么該COOKIE就和這個域相關,只對該網址起作用,當瀏覽該網址時,瀏覽器將把該COOKIE的內容發送給服務端,COOKIE是作為HTTP HEADER的一部分被發送的,如果沒有設置域,那么COOKIE就只和創建該COOKIE的服務器相關.
路徑用于指定服務器上可以使用該COOKIE的文件所在的路徑,它只對該網址下的該路徑下的應用起作用."/"表示服務器上所有目錄都可以使用該COOKIE.
COOKIE都有一個有效期,有效期默認值為-1,這表示沒有保存該COOKIE,當該瀏覽器退出時,該COOKIE立即失效.
安全選項true/false,如果設置為true,那么在服務端與在客戶端之間傳送該COOKIE的內容時,采用HTTPS協議.
如何檢查一個客戶端是否支持COOKIE的方法:
用下面的方法寫一個COOKIE到客戶端,并確認成功
try
{
Cookie c = new Cookie("mycookie","COOKIE TEST");
response.addCookie(c);
}
catch(Exception e)
{
????? System.out.println(e);
}

然后在一個新的JSP文件中:用下面的方法取客戶端的COOKIE到cookies中, 如果cookies.length ==0,說明該客戶端的瀏覽器不支持COOKIE
try
{
Cookie[] cookies = request.getCookies();
if(cookies.length ==0)
{
????? System.out.println("not support cookie");
}
}
catch(Exception e)
{
????? System.out.println(e);
}

2.動態INCLUDE
用jsp:include動作實現 <jsp:include page="included.jsp" flush="true" />它總是會檢查所含文件中的變化,適合用于包含動態頁面,并且可以帶參數。
靜態INCLUDE
用include偽碼實現,定不會檢查所含文件的變化,適用于包含靜態頁面<%@ include file="included.htm" %>
===================================================================
1. 靜態include的結果是把其他jsp引入當前jsp,兩者合為一體
動態include的結構是兩者獨立,直到輸出時才合并( 看看jsp生成的java文件就可以知道了)
2.正是因為這樣,動態include的jsp文件獨立性很強,是一個單獨的jsp文件,需要使用的對象,頁面設置,都必須有自己創建,當然,還好它和include它的頁面的request范圍是一致的.
而靜態include純粹是把代碼寫在外面的一種共享方法,所有的變量都是可以和include它的主文件共享,兩者高度緊密結合,不能有變量同名的沖突.而頁面設置也可以借用主文件的.
詳細出處參考:http://www.jb51.net/article/13159.htm


飛熊 2010-02-08 17:33 發表評論
]]>
圖片壓縮和縮略圖[JAVA]http://www.aygfsteel.com/kyleYang/archive/2010/01/25/310709.html飛熊飛熊Mon, 25 Jan 2010 03:30:00 GMThttp://www.aygfsteel.com/kyleYang/archive/2010/01/25/310709.htmlhttp://www.aygfsteel.com/kyleYang/comments/310709.htmlhttp://www.aygfsteel.com/kyleYang/archive/2010/01/25/310709.html#Feedback0http://www.aygfsteel.com/kyleYang/comments/commentRss/310709.htmlhttp://www.aygfsteel.com/kyleYang/services/trackbacks/310709.html閱讀全文

飛熊 2010-01-25 11:30 發表評論
]]>
java 數字格式化:小數點、百分比http://www.aygfsteel.com/kyleYang/archive/2010/01/17/309863.html飛熊飛熊Sun, 17 Jan 2010 09:13:00 GMThttp://www.aygfsteel.com/kyleYang/archive/2010/01/17/309863.htmlhttp://www.aygfsteel.com/kyleYang/comments/309863.htmlhttp://www.aygfsteel.com/kyleYang/archive/2010/01/17/309863.html#Feedback0http://www.aygfsteel.com/kyleYang/comments/commentRss/309863.htmlhttp://www.aygfsteel.com/kyleYang/services/trackbacks/309863.html1.Decimalformat df1 = new Decimalformat("####.000");
  
????? System.out.println(df1.format(1234.56));

???? 顯示:1234.560

2.Numberformat nf = Numberformat.getPercentInstance();
  
  System.out.println(nf.format(0.47));

???? 顯示:47%

3.DecimalFormat?? df?? =?? new?? DecimalFormat("###,##0.00");

????? System.out.println(nf.format(24.7));

??? 顯示:24.70

????? System.out.println(nf.format(23123.47));

??? 顯示:123,23.47



飛熊 2010-01-17 17:13 發表評論
]]>
對Java配置文件Properties的讀取、寫入與更新操作http://www.aygfsteel.com/kyleYang/archive/2010/01/17/309862.html飛熊飛熊Sun, 17 Jan 2010 09:04:00 GMThttp://www.aygfsteel.com/kyleYang/archive/2010/01/17/309862.htmlhttp://www.aygfsteel.com/kyleYang/comments/309862.htmlhttp://www.aygfsteel.com/kyleYang/archive/2010/01/17/309862.html#Feedback0http://www.aygfsteel.com/kyleYang/comments/commentRss/309862.htmlhttp://www.aygfsteel.com/kyleYang/services/trackbacks/309862.htmlString filepath=System.getProperty("user.dir");

對下面的程序很有用...

/**
* 實現對Java配置文件Properties的讀取、寫入與更新操作
*/
package test;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;


/**
* @author
* @version 2008.11.14
*/
public class SetSystemProperty {
??? //屬性文件的路徑
??? static String profilepath="mail.properties";
??? /**
??? * 采用靜態方法
??? */
??? private static Properties props = new Properties();
??? static {
??????? try {
??????????? props.load(new FileInputStream(profilepath));
??????? } catch (FileNotFoundException e) {
??????????? e.printStackTrace();
??????????? System.exit(-1);
??????? } catch (IOException e) {???????
??????????? System.exit(-1);
??????? }
??? }

??? /**
??? * 讀取屬性文件中相應鍵的值
??? * @param key
??? *??????????? 主鍵
??? * @return String
??? */
??? public static String getKeyValue(String key) {
??????? return props.getProperty(key);
??? }

??? /**
??? * 根據主鍵key讀取主鍵的值value
??? * @param filePath 屬性文件路徑
??? * @param key 鍵名
??? */
??? public static String readValue(String filePath, String key) {
??????? Properties props = new Properties();
??????? try {
??????????? InputStream in = new BufferedInputStream(new FileInputStream(
??????????????????? filePath));
??????????? props.load(in);
??????????? String value = props.getProperty(key);
??????????? System.out.println(key +"鍵的值是:"+ value);
??????????? return value;
??????? } catch (Exception e) {
??????????? e.printStackTrace();
??????????? return null;
??????? }
??? }
???
??? /**
??? * 更新(或插入)一對properties信息(主鍵及其鍵值)
??? * 如果該主鍵已經存在,更新該主鍵的值;
??? * 如果該主鍵不存在,則插件一對鍵值。
??? * @param keyname 鍵名
??? * @param keyvalue 鍵值
??? */
??? public static void writeProperties(String keyname,String keyvalue) {???????
??????? try {
??????????? // 調用 Hashtable 的方法 put,使用 getProperty 方法提供并行性。
??????????? // 強制要求為屬性的鍵和值使用字符串。返回值是 Hashtable 調用 put 的結果。
??????????? OutputStream fos = new FileOutputStream(profilepath);
??????????? props.setProperty(keyname, keyvalue);
??????????? // 以適合使用 load 方法加載到 Properties 表中的格式,
??????????? // 將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出流
??????????? props.store(fos, "Update '" + keyname + "' value");
??????? } catch (IOException e) {
??????????? System.err.println("屬性文件更新錯誤");
??????? }
??? }

??? /**
??? * 更新properties文件的鍵值對
??? * 如果該主鍵已經存在,更新該主鍵的值;
??? * 如果該主鍵不存在,則插件一對鍵值。
??? * @param keyname 鍵名
??? * @param keyvalue 鍵值
??? */
??? public void updateProperties(String keyname,String keyvalue) {
??????? try {
??????????? props.load(new FileInputStream(profilepath));
??????????? // 調用 Hashtable 的方法 put,使用 getProperty 方法提供并行性。
??????????? // 強制要求為屬性的鍵和值使用字符串。返回值是 Hashtable 調用 put 的結果。
??????????? OutputStream fos = new FileOutputStream(profilepath);???????????
??????????? props.setProperty(keyname, keyvalue);
??????????? // 以適合使用 load 方法加載到 Properties 表中的格式,
??????????? // 將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出流
??????????? props.store(fos, "Update '" + keyname + "' value");
??????? } catch (IOException e) {
??????????? System.err.println("屬性文件更新錯誤");
??????? }
??? }
??? //測試代碼
??? public static void main(String[] args) {
??????? readValue("mail.properties", "MAIL_SERVER_PASSWORD");
??????? writeProperties("MAIL_SERVER_INCOMING", "327@qq.com");???????
??????? System.out.println("操作完成");
??? }
}



飛熊 2010-01-17 17:04 發表評論
]]>
Java反射經典實例http://www.aygfsteel.com/kyleYang/archive/2010/01/14/309547.html飛熊飛熊Thu, 14 Jan 2010 13:32:00 GMThttp://www.aygfsteel.com/kyleYang/archive/2010/01/14/309547.htmlhttp://www.aygfsteel.com/kyleYang/comments/309547.htmlhttp://www.aygfsteel.com/kyleYang/archive/2010/01/14/309547.html#Feedback0http://www.aygfsteel.com/kyleYang/comments/commentRss/309547.htmlhttp://www.aygfsteel.com/kyleYang/services/trackbacks/309547.htmlJava反射經典實例 Java Reflection Cookbook
Java提供了一套機制來動態執行方法和構造方法,以及數組操作等,這套機制就叫——反射。反射機制是如今很多流行框架的實現基礎,其中包括Spring、Hibernate等。原理性的問題不是本文的重點,接下來讓我們在實例中學習這套精彩的機制。

1. 得到某個對象的屬性

1?public?Object getProperty(Object owner, String fieldName)?throws?Exception {
2?????Class ownerClass?=?owner.getClass();
3?
4?????Field field?=?ownerClass.getField(fieldName);
5?
6?????Object property?=?field.get(owner);
7?
8?????return?property;
9?}

Class ownerClass = owner.getClass():得到該對象的Class。

Field field = ownerClass.getField(fieldName):通過Class得到類聲明的屬性。

Object property = field.get(owner):通過對象得到該屬性的實例,如果這個屬性是非公有的,這里會報IllegalAccessException。



2. 得到某個類的靜態屬性

?1?public?Object getStaticProperty(String className, String fieldName)
?2?????????????throws?Exception {
?3?????Class ownerClass?=?Class.forName(className);
?4?
?5?????Field field?=?ownerClass.getField(fieldName);
?6?
?7?????Object property?=?field.get(ownerClass);
?8?
?9?????return?property;
10?}


Class ownerClass = Class.forName(className) :首先得到這個類的Class。

Field field = ownerClass.getField(fieldName):和上面一樣,通過Class得到類聲明的屬性。

Object property = field.get(ownerClass) :這里和上面有些不同,因為該屬性是靜態的,所以直接從類的Class里取。


3. 執行某對象的方法

?1?public?Object invokeMethod(Object owner, String methodName, Object[] args)?throws?Exception {
?2?
?3?????Class ownerClass?=?owner.getClass();
?4?
?5?????Class[] argsClass?=?new?Class[args.length];
?6?
?7?????for?(int?i?=?0, j?=?args.length; i?<?j; i++) {
?8?????????argsClass[i]?=?args[i].getClass();
?9?????}
10?
11?????Method method?=?ownerClass.getMethod(methodName, argsClass);
12?
13?????return?method.invoke(owner, args);
14?}

Class owner_class = owner.getClass() :首先還是必須得到這個對象的Class。

5~9行:配置參數的Class數組,作為尋找Method的條件。

Method method = ownerClass.getMethod(methodName, argsClass):通過Method名和參數的Class數組得到要執行的Method。

method.invoke(owner, args):執行該Method,invoke方法的參數是執行這個方法的對象,和參數數組。返回值是Object,也既是該方法的返回值。


4. 執行某個類的靜態方法

?1?public?Object invokeStaticMethod(String className, String methodName,
?2?????????????Object[] args)?throws?Exception {
?3?????Class ownerClass?=?Class.forName(className);
?4?
?5?????Class[] argsClass?=?new?Class[args.length];
?6?
?7?????for?(int?i?=?0, j?=?args.length; i?<?j; i++) {
?8?????????argsClass[i]?=?args[i].getClass();
?9?????}
10?
11?????Method method?=?ownerClass.getMethod(methodName, argsClass);
12?
13?????return?method.invoke(null, args);
14?}


基本的原理和實例3相同,不同點是最后一行,invoke的一個參數是null,因為這是靜態方法,不需要借助實例運行。



5. 新建實例
?1?
?2?public?Object newInstance(String className, Object[] args)?throws?Exception {
?3?????Class newoneClass?=?Class.forName(className);
?4?
?5?????Class[] argsClass?=?new?Class[args.length];
?6?
?7?????for?(int?i?=?0, j?=?args.length; i?<?j; i++) {
?8?????????argsClass[i]?=?args[i].getClass();
?9?????}
10?
11?????Constructor cons?=?newoneClass.getConstructor(argsClass);
12?
13?????return?cons.newInstance(args);
14?
15?}


這里說的方法是執行帶參數的構造函數來新建實例的方法。如果不需要參數,可以直接使用newoneClass.newInstance()來實現。

Class newoneClass = Class.forName(className):第一步,得到要構造的實例的Class。

第5~第9行:得到參數的Class數組。

Constructor cons = newoneClass.getConstructor(argsClass):得到構造子。

cons.newInstance(args):新建實例。


6. 判斷是否為某個類的實例

1?public?boolean?isInstance(Object obj, Class cls) {
2?????return?cls.isInstance(obj);
3?}



7. 得到數組中的某個元素
1?public?Object getByArray(Object array,?int?index) {
2?????return?Array.get(array,index);
3?}



附完整源碼:

import?java.lang.reflect.Array;
import?java.lang.reflect.Constructor;
import?java.lang.reflect.Field;
import?java.lang.reflect.Method;


/**
?* Java Reflection Cookbook
?*
?*?
@author?Michael Lee
?*?
@since?2006-8-23
?*?
@version?0.1a
?
*/

public?class?Reflection {
????
/**
?????* 得到某個對象的公共屬性
?????*
?????*?
@param?owner, fieldName
?????*?
@return?該屬性對象
?????*?
@throws?Exception
?????*
?????
*/
????
public?Object getProperty(Object owner, String fieldName)?throws?Exception {
????????Class ownerClass?
=?owner.getClass();

????????Field field?
=?ownerClass.getField(fieldName);

????????Object property?
=?field.get(owner);

????????
return?property;
????}

????
/**
?????* 得到某類的靜態公共屬性
?????*
?????*?
@param?className?? 類名
?????*?
@param?fieldName?? 屬性名
?????*?
@return?該屬性對象
?????*?
@throws?Exception
?????
*/
????
public?Object getStaticProperty(String className, String fieldName)
????????????
throws?Exception {
????????Class ownerClass?
=?Class.forName(className);

????????Field field?
=?ownerClass.getField(fieldName);

????????Object property?
=?field.get(ownerClass);

????????
return?property;
????}


????
/**
?????* 執行某對象方法
?????*
?????*?
@param?owner
?????*??????????? 對象
?????*?
@param?methodName
?????*??????????? 方法名
?????*?
@param?args
?????*??????????? 參數
?????*?
@return?方法返回值
?????*?
@throws?Exception
?????
*/
????
public?Object invokeMethod(Object owner, String methodName, Object[] args)
????????????
throws?Exception {

????????Class ownerClass?
=?owner.getClass();

????????Class[] argsClass?
=?new?Class[args.length];

????????
for?(int?i?=?0, j?=?args.length; i?<?j; i++) {
????????????argsClass[i]?
=?args[i].getClass();
????????}

????????Method method?
=?ownerClass.getMethod(methodName, argsClass);

????????
return?method.invoke(owner, args);
????}


??????
/**
?????* 執行某類的靜態方法
?????*
?????*?
@param?className
?????*??????????? 類名
?????*?
@param?methodName
?????*??????????? 方法名
?????*?
@param?args
?????*??????????? 參數數組
?????*?
@return?執行方法返回的結果
?????*?
@throws?Exception
?????
*/
????
public?Object invokeStaticMethod(String className, String methodName,
????????????Object[] args)?
throws?Exception {
????????Class ownerClass?
=?Class.forName(className);

????????Class[] argsClass?
=?new?Class[args.length];

????????
for?(int?i?=?0, j?=?args.length; i?<?j; i++) {
????????????argsClass[i]?
=?args[i].getClass();
????????}

????????Method method?
=?ownerClass.getMethod(methodName, argsClass);

????????
return?method.invoke(null, args);
????}



????
/**
?????* 新建實例
?????*
?????*?
@param?className
?????*??????????? 類名
?????*?
@param?args
?????*??????????? 構造函數的參數
?????*?
@return?新建的實例
?????*?
@throws?Exception
?????
*/
????
public?Object newInstance(String className, Object[] args)?throws?Exception {
????????Class newoneClass?
=?Class.forName(className);

????????Class[] argsClass?
=?new?Class[args.length];

????????
for?(int?i?=?0, j?=?args.length; i?<?j; i++) {
????????????argsClass[i]?
=?args[i].getClass();
????????}

????????Constructor cons?
=?newoneClass.getConstructor(argsClass);

????????
return?cons.newInstance(args);

????}


????
????
/**
?????* 是不是某個類的實例
?????*?
@param?obj 實例
?????*?
@param?cls 類
?????*?
@return?如果 obj 是此類的實例,則返回 true
?????
*/
????
public?boolean?isInstance(Object obj, Class cls) {
????????
return?cls.isInstance(obj);
????}
????
????
/**
?????* 得到數組中的某個元素
?????*?
@param?array 數組
?????*?
@param?index 索引
?????*?
@return?返回指定數組對象中索引組件的值
?????
*/
????
public?Object getByArray(Object array,?int?index) {
????????
return?Array.get(array,index);
????}
}



飛熊 2010-01-14 21:32 發表評論
]]>
java中的過濾器Filter的使用配置http://www.aygfsteel.com/kyleYang/archive/2010/01/08/308744.html飛熊飛熊Fri, 08 Jan 2010 09:07:00 GMThttp://www.aygfsteel.com/kyleYang/archive/2010/01/08/308744.htmlhttp://www.aygfsteel.com/kyleYang/comments/308744.htmlhttp://www.aygfsteel.com/kyleYang/archive/2010/01/08/308744.html#Feedback0http://www.aygfsteel.com/kyleYang/comments/commentRss/308744.htmlhttp://www.aygfsteel.com/kyleYang/services/trackbacks/308744.html  import java.io.PrintWriter;
  import javax.servlet.Filter;
  import javax.servlet.FilterChain;
  import javax.servlet.FilterConfig;
  import javax.servlet.RequestDispatcher;
  import javax.servlet.ServletException;
  import javax.servlet.ServletRequest;
  import javax.servlet.ServletResponse;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import javax.servlet.http.HttpSession;
  /**
  * 過濾器使用:用戶沒用登錄,不可以在瀏覽器輸入地址訪問頁面
  * @author Administrator
  *
  */
  public class OnlineFilter extends HttpServlet implements Filter {
?  public void doFilter(ServletRequest request, ServletResponse response,
??  FilterChain chain) throws IOException, ServletException {
??  RequestDispatcher dispatcher = request.getRequestDispatcher("Login.jsp");
??  HttpServletRequest req =(HttpServletRequest)request;
??  HttpServletResponse res =(HttpServletResponse)response;
??  HttpSession session =req.getSession(true);
??  //從session 里面獲取用戶名的信息
??  String user =(String)session.getAttribute("user");
??  //判斷如果沒有取到用戶信息,就跳轉到登陸頁面,提示用戶進行登陸
????? if(user == null || "".equals(user)){
???  //跳轉到登陸的頁面,進行用戶登錄
???  dispatcher.forward(request,response);
???  System.out.println("用戶沒有登錄,請登陸!");
??  }else{
??  ?System.out.println("用戶已經登陸成功,允許繼續操作!");
??  }
??  chain.doFilter(request, response);
?  }
?  public void init(FilterConfig arg0) throws ServletException {
?  }
?  /**
?  * Destruction of the servlet. <br>
?  */
?  public void destroy() {
?  super.destroy(); // Just puts "destroy" string in log
?  }
?  public void init() throws ServletException {
?  }
  }
  Web.xml配置
  <!-- 過濾器的? 過濾用戶登陸的session對象 -->
  <filter>
  <filter-name>sessionFilter</filter-name>
  <filter-class>biz.sdna.cbrc.util.OnlineFilter</filter-class>
  </filter>
  <filter-mapping>
  <filter-name>sessionFilter</filter-name>
  <url-pattern>/jsp/*</url-pattern>
  </filter-mapping>

飛熊 2010-01-08 17:07 發表評論
]]>
Java讀寫Excelhttp://www.aygfsteel.com/kyleYang/archive/2009/12/19/306700.html飛熊飛熊Sat, 19 Dec 2009 15:46:00 GMThttp://www.aygfsteel.com/kyleYang/archive/2009/12/19/306700.htmlhttp://www.aygfsteel.com/kyleYang/comments/306700.htmlhttp://www.aygfsteel.com/kyleYang/archive/2009/12/19/306700.html#Feedback0http://www.aygfsteel.com/kyleYang/comments/commentRss/306700.htmlhttp://www.aygfsteel.com/kyleYang/services/trackbacks/306700.html本文主要向你演示如何使用JavaExcel API來讀寫Excel文件。關于JavaExcel API,這是一個開源的lib庫。其相關的feature如下:

支持Excel 95, 97, 2000, XP, 2003 的制表頁。
可以讀寫相關的Excel公式 (僅支持Excel 97 及以后版本)
可以生成 Excel 2000 格式的xls文件。
支持字體,數字和日期格式。
支持單元格的陰影,邊框和顏色。
可以修改已存在的制表頁。
國際化多語言集。(公式目前支持,英文,法文,西班牙文和德文)
支持圖表拷貝。
支持圖片的插入和復制。
日志生成可以使用Jakarta Commons Logging, log4j, JDK 1.4 Logger, 等。
更多……
你可以在這里下載:http://jexcelapi.sourceforge.net/,然后,把jxl.jar加到你的Java的classpath中。

下面是兩段例程,一段是如何創建Excel,一段是如何讀取Excel。


創建Excel

?packagewriter;?

???

?importjava.io.File;?

?importjava.io.IOException;?

?importjava.util.Locale;?

???

?importjxl.CellView;?

?importjxl.Workbook;?

?importjxl.WorkbookSettings;?

?importjxl.format.UnderlineStyle;?

?importjxl.write.Formula;?

?importjxl.write.Label;?

?importjxl.write.Number;?

?importjxl.write.WritableCellFormat;?

?importjxl.write.WritableFont;?

?importjxl.write.WritableSheet;?

?importjxl.write.WritableWorkbook;?

?importjxl.write.WriteException;?

?importjxl.write.biff.RowsExceededException;?

???

?publicclassWriteExcel {?

???

???? privateWritableCellFormat timesBoldUnderline;?

???? privateWritableCellFormat times;?

???? privateString inputFile;?

???

?publicvoidsetOutputFile(String inputFile) {?

???? this.inputFile = inputFile;?

???? }?

???

???? publicvoidwrite() throwsIOException, WriteException {?

???????? File file = newFile(inputFile);?

???????? WorkbookSettings wbSettings = newWorkbookSettings();?

???

???????? wbSettings.setLocale(newLocale("en", "EN"));?

???

???????? WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);?

???????? workbook.createSheet("Report", 0);?

???????? WritableSheet excelSheet = workbook.getSheet(0);?

???????? createLabel(excelSheet);?

???????? createContent(excelSheet);?

???

???????? workbook.write();?

???????? workbook.close();?

???? }?

???

???? privatevoidcreateLabel(WritableSheet sheet)?

???????????? throwsWriteException {?

???????? // Lets create a times font?

???????? WritableFont times10pt = newWritableFont(WritableFont.TIMES, 10);?

???????? // Define the cell format?

???????? times = newWritableCellFormat(times10pt);?

???????? // Lets automatically wrap the cells?

???????? times.setWrap(true);?

???

???????? // Create create a bold font with unterlines?

???????? WritableFont times10ptBoldUnderline = newWritableFont(?

???????????????? WritableFont.TIMES, 10, WritableFont.BOLD, false,?

???????????????? UnderlineStyle.SINGLE);?

???????? timesBoldUnderline = newWritableCellFormat(times10ptBoldUnderline);?

???????? // Lets automatically wrap the cells?

???????? timesBoldUnderline.setWrap(true);?

???

???????? CellView cv = newCellView();?

???????? cv.setFormat(times);?

???????? cv.setFormat(timesBoldUnderline);?

???????? cv.setAutosize(true);?

???

???????? // Write a few headers?

???????? addCaption(sheet, 0, 0, "Header 1");?

???????? addCaption(sheet, 1, 0, "This is another header");?

???

???? }?

???

???? privatevoidcreateContent(WritableSheet sheet) throwsWriteException,?

???????????? RowsExceededException {?

???????? // Write a few number?

???????? for(inti = 1; i < 10; i++) {?

???????????? // First column?

???????????? addNumber(sheet, 0, i, i + 10);?

???????????? // Second column?

???????????? addNumber(sheet, 1, i, i * i);?

???????? }?

???????? // Lets calculate the sum of it?

???????? StringBuffer buf = newStringBuffer();?

???????? buf.append("SUM(A2:A10)");?

???????? Formula f = newFormula(0, 10, buf.toString());?

???????? sheet.addCell(f);?

???????? buf = newStringBuffer();?

???????? buf.append("SUM(B2:B10)");?

???????? f = newFormula(1, 10, buf.toString());?

???????? sheet.addCell(f);?

???

???????? // Now a bit of text?

???????? for(inti = 12; i < 20; i++) {?

???????????? // First column?

???????????? addLabel(sheet, 0, i, "Boring text "+ i);?

???????????? // Second column?

???????????? addLabel(sheet, 1, i, "Another text");?

???????? }?

???? }?

???

???? privatevoidaddCaption(WritableSheet sheet, intcolumn, introw, String s)?

???????????? throwsRowsExceededException, WriteException {?

???????? Label label;?

???????? label = newLabel(column, row, s, timesBoldUnderline);?

???????? sheet.addCell(label);?

???? }?

???

???? privatevoidaddNumber(WritableSheet sheet, intcolumn, introw,?

???????????? Integer integer) throwsWriteException, RowsExceededException {?

???????? Number number;?

???????? number = newNumber(column, row, integer, times);?

???????? sheet.addCell(number);?

???? }?

???

???? privatevoidaddLabel(WritableSheet sheet, intcolumn, introw, String s)?

???????????? throwsWriteException, RowsExceededException {?

???????? Label label;?

???????? label = newLabel(column, row, s, times);?

???????? sheet.addCell(label);?

???? }?

???

???? publicstaticvoidmain(String[] args) throwsWriteException, IOException {?

???????? WriteExcel test = newWriteExcel();?

???????? test.setOutputFile("c:/temp/lars.xls");?

???????? test.write();?

???????? System.out?

???????????????? .println("Please check the result file under c:/temp/lars.xls ");?

???? }?

?}


讀取Excel

?packagereader;?

???

?importjava.io.File;?

?importjava.io.IOException;?

???

?importjxl.Cell;?

?importjxl.CellType;?

?importjxl.Sheet;?

?importjxl.Workbook;?

?importjxl.read.biff.BiffException;?

???

?publicclassReadExcel {?

???

???? privateString inputFile;?

???

???? publicvoidsetInputFile(String inputFile) {?

???????? this.inputFile = inputFile;?

???? }?

???

???? publicvoidread() throwsIOException? {?

???????? File inputWorkbook = newFile(inputFile);?

???????? Workbook w;?

???????? try{?

???????????? w = Workbook.getWorkbook(inputWorkbook);?

???????????? // Get the first sheet?

???????????? Sheet sheet = w.getSheet(0);?

???????????? // Loop over first 10 column and lines?

???

???????????? for(intj = 0; j < sheet.getColumns(); j++) {?

???????????????? for(inti = 0; i < sheet.getRows(); i++) {?

???????????????????? Cell cell = sheet.getCell(j, i);?

???????????????????? CellType type = cell.getType();?

???????????????????? if(cell.getType() == CellType.LABEL) {?

???????????????????????? System.out.println("I got a label "

???????????????????????????????? + cell.getContents());?

???????????????????? }?

???

???????????????????? if(cell.getType() == CellType.NUMBER) {?

???????????????????????? System.out.println("I got a number "

???????????????????????????????? + cell.getContents());?

???????????????????? }?

???

???????????????? }?

???????????? }?

???????? } catch(BiffException e) {?

???????????? e.printStackTrace();?

???????? }?

???? }?

???? publicstaticvoidmain(String[] args) throwsIOException {?

???????? ReadExcel test = newReadExcel();?

???????? test.setInputFile("c:/temp/lars.xls");?

???????? test.read();?

???? }?

?}



飛熊 2009-12-19 23:46 發表評論
]]>
Java中的堆內存與棧內存分配淺析http://www.aygfsteel.com/kyleYang/archive/2009/12/11/305612.html飛熊飛熊Fri, 11 Dec 2009 09:26:00 GMThttp://www.aygfsteel.com/kyleYang/archive/2009/12/11/305612.htmlhttp://www.aygfsteel.com/kyleYang/comments/305612.htmlhttp://www.aygfsteel.com/kyleYang/archive/2009/12/11/305612.html#Feedback0http://www.aygfsteel.com/kyleYang/comments/commentRss/305612.htmlhttp://www.aygfsteel.com/kyleYang/services/trackbacks/305612.html??????Java 把內存劃分成兩種:一種是棧內存,另一種是堆內存。在函數中定義的一些基本類型的變量和對象的引用變量都是在函數的棧內存中分配,當在一段代碼塊定義一個變量時,Java 就在棧中為這個變量分配內存空間,當超過變量的作用域后,Java 會自動釋放掉為該變量分配的內存空間,該內存空間可以立即被另作它用。

??????堆內存用來存放由 new 創建的對象和數組,在堆中分配的內存,由 Java 虛擬機的自動垃圾回收器來管理。在堆中產生了一個數組或者對象之后,還可以在棧中定義一個特殊的變量,讓棧中的這個變量的取值等于數組或對象在堆內存中的首地址,棧中的這個變量就成了數組或對象的引用變量,以后就可以在程序中使用棧中的引用變量來訪問堆中的數組或者對象,引用變量就相當于是為數組或者對象起的一個名稱。引用變量是普通的變量,定義時在棧中分配,引用變量在程序運行到其作用域之外后被釋放。而數組和對象本身在堆中分配,即使程序運行到使用 new 產生數組或者對象的語句所在的代碼塊之外,數組和對象本身占據的內存不會被釋放,數組和對象在沒有引用變量指向它的時候,才變為垃圾,不能在被使用,但仍然占據內存空間不放,在隨后的一個不確定的時間被垃圾回收器收走(釋放掉)。

??????這也是 Java 比較占內存的原因,實際上,棧中的變量指向堆內存中的變量,這就是 Java 中的指針!



飛熊 2009-12-11 17:26 發表評論
]]>
java 圖片切割,縮放,轉換類型http://www.aygfsteel.com/kyleYang/archive/2009/12/07/305002.html飛熊飛熊Mon, 07 Dec 2009 07:03:00 GMThttp://www.aygfsteel.com/kyleYang/archive/2009/12/07/305002.htmlhttp://www.aygfsteel.com/kyleYang/comments/305002.htmlhttp://www.aygfsteel.com/kyleYang/archive/2009/12/07/305002.html#Feedback0http://www.aygfsteel.com/kyleYang/comments/commentRss/305002.htmlhttp://www.aygfsteel.com/kyleYang/services/trackbacks/305002.htmlimport java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.Graphics;
import java.awt.color.ColorSpace;
import javax.imageio.ImageIO;

public class ImageCut {
?/**
? * 縮放圖像
? *
? * @param srcImageFile
? *??????????? 源圖像文件地址
? * @param result
? *??????????? 縮放后的圖像地址
? * @param scale
? *??????????? 縮放比例
? * @param flag
? *??????????? 縮放選擇:true 放大; false 縮小;
? */
?public static void scale(String srcImageFile, String result, int scale,
???boolean flag) {
??try {
???BufferedImage src = ImageIO.read(new File(srcImageFile)); // 讀入文件
???int width = src.getWidth(); // 得到源圖寬
???int height = src.getHeight(); // 得到源圖長
???if (flag) {
????// 放大
????width = width * scale;
????height = height * scale;
???} else {
????// 縮小
????width = width / scale;
????height = height / scale;
???}
???Image image = src.getScaledInstance(width, height,
?????Image.SCALE_DEFAULT);
???BufferedImage tag = new BufferedImage(width, height,
?????BufferedImage.TYPE_INT_RGB);
???Graphics g = tag.getGraphics();
???g.drawImage(image, 0, 0, null); // 繪制縮小后的圖
???g.dispose();
???ImageIO.write(tag, "JPEG", new File(result));// 輸出到文件流
??} catch (IOException e) {
???e.printStackTrace();
??}
?}

?/**
? * 圖像切割
? *
? * @param srcImageFile
? *??????????? 源圖像地址
? * @param descDir
? *??????????? 切片目標文件夾
? * @param destWidth
? *??????????? 目標切片寬度
? * @param destHeight
? *??????????? 目標切片高度
? */
?public static void cut(String srcImageFile, String descDir, int destWidth,
???int destHeight) {
??try {
???Image img;
???ImageFilter cropFilter;
???// 讀取源圖像
???BufferedImage bi = ImageIO.read(new File(srcImageFile));
???int srcWidth = bi.getHeight(); // 源圖寬度
???int srcHeight = bi.getWidth(); // 源圖高度
???if (srcWidth > destWidth && srcHeight > destHeight) {
????Image image = bi.getScaledInstance(srcWidth, srcHeight,
??????Image.SCALE_DEFAULT);
????destWidth = 200; // 切片寬度
????destHeight = 150; // 切片高度
????int cols = 0; // 切片橫向數量
????int rows = 0; // 切片縱向數量
????// 計算切片的橫向和縱向數量
????if (srcWidth % destWidth == 0) {
?????cols = srcWidth / destWidth;
????} else {
?????cols = (int) Math.floor(srcWidth / destWidth) + 1;
????}
????if (srcHeight % destHeight == 0) {
?????rows = srcHeight / destHeight;
????} else {
?????rows = (int) Math.floor(srcHeight / destHeight) + 1;
????}
????// 循環建立切片
????// 改進的想法:是否可用多線程加快切割速度
????for (int i = 0; i < rows; i++) {
?????for (int j = 0; j < cols; j++) {
??????// 四個參數分別為圖像起點坐標和寬高
??????// 即: CropImageFilter(int x,int y,int width,int height)
??????cropFilter = new CropImageFilter(j * 200, i * 150,
????????destWidth, destHeight);
??????img = Toolkit.getDefaultToolkit().createImage(
????????new FilteredImageSource(image.getSource(),
??????????cropFilter));
??????BufferedImage tag = new BufferedImage(destWidth,
????????destHeight, BufferedImage.TYPE_INT_RGB);
??????Graphics g = tag.getGraphics();
??????g.drawImage(img, 0, 0, null); // 繪制縮小后的圖
??????g.dispose();
??????// 輸出為文件
??????ImageIO.write(tag, "JPEG", new File(descDir
????????+ "pre_map_" + i + "_" + j + ".jpg"));
?????}
????}
???}
??} catch (Exception e) {
???e.printStackTrace();
??}
?}

?/**
? * 圖像類型轉換 GIF->JPG GIF->PNG PNG->JPG PNG->GIF(X)
? */
?public static void convert(String source, String result) {
??try {
???File f = new File(source);
???f.canRead();
???f.canWrite();
???BufferedImage src = ImageIO.read(f);
???ImageIO.write(src, "JPG", new File(result));
??} catch (Exception e) {
???// TODO Auto-generated catch block
???e.printStackTrace();
??}
?}

?/**
? * 彩色轉為黑白
? *
? * @param source
? * @param result
? */
?public static void gray(String source, String result) {
??try {
???BufferedImage src = ImageIO.read(new File(source));
???ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
???ColorConvertOp op = new ColorConvertOp(cs, null);
???src = op.filter(src, null);
???ImageIO.write(src, "JPEG", new File(result));
??} catch (IOException e) {
???e.printStackTrace();
??}
?}

?/**
? * @param args
? */
?public static void main(String[] args) {
? ?? cut("D:/logo.gif", "D:/", 20, 15);
?????convert("D:/logo.gif", "D:/temp.png");
?}
}



飛熊 2009-12-07 15:03 發表評論
]]>
JSP連接遠程FTP服務器,生成縮略圖http://www.aygfsteel.com/kyleYang/archive/2009/12/07/305000.html飛熊飛熊Mon, 07 Dec 2009 06:24:00 GMThttp://www.aygfsteel.com/kyleYang/archive/2009/12/07/305000.htmlhttp://www.aygfsteel.com/kyleYang/comments/305000.htmlhttp://www.aygfsteel.com/kyleYang/archive/2009/12/07/305000.html#Feedback0http://www.aygfsteel.com/kyleYang/comments/commentRss/305000.htmlhttp://www.aygfsteel.com/kyleYang/services/trackbacks/305000.html 圖片文件放在遠程FTP服務器上,圖片是用作宣傳的,很大。用戶只能訪問web服務器,用戶需要在web上先預覽圖片的縮略圖,然后點擊鏈接下載該圖片。

目前有兩種解決方案
第一種方案,通過web服務器的jsp去連接ftp客戶端,讀取到遠程FTP服務器上的圖片,生成縮略圖,返回到頁面,然后用戶選擇想下載的圖片,再一次通過jsp連接ftp下載到客戶端。
示例代碼如下:
<%-- 
    Document   : img
    Created on : 
2007-10-300:02:28
    Author     : autumn
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.awt.image.BufferedImage" %>
<%@ page import="java.awt.*" %>
<%@ page import="com.sun.image.codec.jpeg.*" %>
<%@ page import="sun.net.ftp.FtpClient" %>
<%@ page import="sun.net.TelnetInputStream" %>
<%@ page import="java.io.ByteArrayOutputStream" %>
<%
 
String path 
= request.getParameter("path");

try {
  response.flushBuffer();
  out.clear();
  out 
= pageContext.pushBody();
 
  out.clear();
  response.setContentType(
"image/jpg");
  response.addHeader(
"pragma","NO-cache");
  response.addHeader(
"Cache-Control","no-cache");
  response.addDateHeader(
"Expries",0);
  
  
/*連接ftp服務器*/
  FtpClient fc 
= new FtpClient();
  fc.openServer(
"127.0.0.1");                 //連接ftp服務器,參數為ftp服務器地址
  fc.login("test""test");                   //登錄ftp服務器,參數為ftp用戶名密碼
  fc.binary();                                //轉成二進制模式
  TelnetInputStream bis = fc.get(path);      //獲取文件,返回輸入流
 
  BufferedImage image 
= javax.imageio.ImageIO.read(bis);
  bis.close();                                
//關閉輸入流
  fc.closeServer();                           //關閉服務器連接
  /*生成縮略圖*/
  
float tag_w=80;
  
float tag_h=60;
  
int old_w=image.getWidth(null);        //得到源圖寬度
  int old_h=image.getHeight(null);       //得到源圖高度
  int new_w=0;                            //縮略圖的寬度
  int new_h=0;                            //縮略圖的高度
 
  
float tempdouble;
  
if(old_w>old_h){
    tempdouble
=old_w/tag_w;
  }
else{
    tempdouble
=old_h/tag_h;
  }

  new_w
=Math.round(old_w/tempdouble);  //計算縮略圖高度
  new_h=Math.round(old_h/tempdouble);  //計算縮略圖寬度
 
  BufferedImage tag 
= new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
  tag.getGraphics().drawImage(image,
0,0,new_w,new_h,null);       //繪制縮小后的圖
 
  ServletOutputStream outStream 
= response.getOutputStream();
  JPEGImageEncoder encoder 
=JPEGCodec.createJPEGEncoder(outStream);
  encoder.encode(tag);
  outStream.close();
  response.reset();
}
 catch (Exception ex) {
 
//異常處理
}

%>

<%-- 
    Document   : main
    Created 
on : 2007-10-300:02:11
    Author     : autumn
--
%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd"
>

<html>
    
<head>
        
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        
<title>JSP Page</title>
    
</head>
    
<body>
        
<h3>FTP img tset</h3>
        
<img src="img.jsp?path=/2.jpg"/>
    
</body>
</html>

上例只實現從遠程獲得圖片生成縮略圖返回,沒有實現遠程下載圖片,不過原理一樣。
這個方案有一個缺點,就是生成縮略圖前,得從ftp服務器讀取大圖,速度比較慢。

第二種解決方案是在遠程ftp服務器架設一個web server,兩個服務器共享文件目錄,把生成縮略圖的工作放在遠程,而傳回來的只是縮略圖,所以速度會快不少。


飛熊 2009-12-07 14:24 發表評論
]]>
StringTokenizer和Splite的區別http://www.aygfsteel.com/kyleYang/archive/2009/11/05/301347.html飛熊飛熊Thu, 05 Nov 2009 15:43:00 GMThttp://www.aygfsteel.com/kyleYang/archive/2009/11/05/301347.htmlhttp://www.aygfsteel.com/kyleYang/comments/301347.htmlhttp://www.aygfsteel.com/kyleYang/archive/2009/11/05/301347.html#Feedback0http://www.aygfsteel.com/kyleYang/comments/commentRss/301347.htmlhttp://www.aygfsteel.com/kyleYang/services/trackbacks/301347.html import java.util.StringTokenizer;

public class TestStringTokenizer {

    public static void main(String[] args) {
        StringTokenizer tokenizer = new StringTokenizer(
                "I am a deve,loper; in shenzhen", " |,|;");
        System.out.println(tokenizer.countTokens());

        while (tokenizer.hasMoreTokens()) {
            // logger.debug(tokenizer.nextToken(" ")); //nextToken(String
            // delim); 下一個分隔符分割的值
           
            System.out.println(tokenizer.nextToken());
        }
    }
}
結果:
7
I
am
a
deve
loper
in
shenzhen

2.Split的例子
public static void main(String[] args) {
        TestSplit ts = new TestSplit();
        System.out.println(ts.bubbleSort("1,32,23 14 5,7"));
    }

    public static String bubbleSort(String str1) {
        String st[] = str1.split(",| ");
        for (int i = 0; i < st.length; i++) {
            for (int j = 0; j < st.length - 1 - i; j++) {
                if (Integer.parseInt(st[j]) > Integer.parseInt(st[j + 1])) {
                    String temp = st[j];
                    st[j] = st[j + 1];
                    st[j + 1] = temp;
                }
            }
        }
        String str2 = "";
        for (int i = 0; i < st.length; i++) {
            if (str2.equals("")) {
                str2 = st[i];
            } else {
                str2 = str2 + "," + st[i];
            }
        }
        return str2;
    }

結果:1,5,7,14,23,32




飛熊 2009-11-05 23:43 發表評論
]]>
JAVA反射機制http://www.aygfsteel.com/kyleYang/archive/2009/11/04/301164.html飛熊飛熊Wed, 04 Nov 2009 14:02:00 GMThttp://www.aygfsteel.com/kyleYang/archive/2009/11/04/301164.htmlhttp://www.aygfsteel.com/kyleYang/comments/301164.htmlhttp://www.aygfsteel.com/kyleYang/archive/2009/11/04/301164.html#Feedback0http://www.aygfsteel.com/kyleYang/comments/commentRss/301164.htmlhttp://www.aygfsteel.com/kyleYang/services/trackbacks/301164.html         1. 得到某個對象的屬性
 public Object getProperty(Object owner, String fieldName) throws Exception {
     Class ownerClass = owner.getClass();
 
    Field field = ownerClass.getField(fieldName);
 
     Object property = field.get(owner);
 
     return property;
 }

Class ownerClass = owner.getClass():得到該對象的Class。

Field field = ownerClass.getField(fieldName):通過Class得到類聲明的屬性。

Object property = field.get(owner):通過對象得到該屬性的實例,如果這個屬性是非公有的,這里會報IllegalAccessException。



2. 得到某個類的靜態屬性

  public Object getStaticProperty(String className, String fieldName)
              throws Exception {
      Class ownerClass = Class.forName(className);
  
      Field field = ownerClass.getField(fieldName);
 
      Object property = field.get(ownerClass);
  
      return property;
 }

Class ownerClass = Class.forName(className) :首先得到這個類的Class。

Field field = ownerClass.getField(fieldName):和上面一樣,通過Class得到類聲明的屬性。

Object property = field.get(ownerClass) :這里和上面有些不同,因為該屬性是靜態的,所以直接從類的Class里取。


3. 執行某對象的方法

  public Object invokeMethod(Object owner, String methodName, Object[] args) throws Exception {
  
      Class ownerClass = owner.getClass();
  
      Class[] argsClass = new Class[args.length];
  
      for (int i = 0, j = args.length; i < j; i++) {
          argsClass[i] = args[i].getClass();
      }
 
     Method method = ownerClass.getMethod(methodName, argsClass);
 
     return method.invoke(owner, args);
 }

Class owner_class = owner.getClass() :首先還是必須得到這個對象的Class。

5~9行:配置參數的Class數組,作為尋找Method的條件。

Method method = ownerClass.getMethod(methodName, argsClass):通過Method名和參數的Class數組得到要執行的Method。

method.invoke(owner, args):執行該Method,invoke方法的參數是執行這個方法的對象,和參數數組。返回值是Object,也既是該方法的返回值。


4. 執行某個類的靜態方法

 public Object invokeStaticMethod(String className, String methodName,
              Object[] args) throws Exception {
      Class ownerClass = Class.forName(className);
  
      Class[] argsClass = new Class[args.length];
  
      for (int i = 0, j = args.length; i < j; i++) {
          argsClass[i] = args[i].getClass();
      }
 
     Method method = ownerClass.getMethod(methodName, argsClass);
 
     return method.invoke(null, args);
 }


飛熊 2009-11-04 22:02 發表評論
]]>
Java實現文件拷貝的4種方法http://www.aygfsteel.com/kyleYang/archive/2009/10/24/299535.html飛熊飛熊Fri, 23 Oct 2009 16:41:00 GMThttp://www.aygfsteel.com/kyleYang/archive/2009/10/24/299535.htmlhttp://www.aygfsteel.com/kyleYang/comments/299535.htmlhttp://www.aygfsteel.com/kyleYang/archive/2009/10/24/299535.html#Feedback0http://www.aygfsteel.com/kyleYang/comments/commentRss/299535.htmlhttp://www.aygfsteel.com/kyleYang/services/trackbacks/299535.html第一種方法:古老的方式

 public static long forJava(File f1,File f2) throws Exception{
  long time=new Date().getTime();
  int length=2097152;
  FileInputStream in=new FileInputStream(f1);
  FileOutputStream out=new FileOutputStream(f2);
  byte[] buffer=new byte[length];
  while(true){
   int ins=in.read(buffer);
   if(ins==-1){
    in.close();
    out.flush();
    out.close();
    return new Date().getTime()-time;
   }else
    out.write(buffer,0,ins);
  }
 }
方法的2參數分別是原始文件,和拷貝的目的文件.這里不做過多介紹.

實現方法很簡單,分別對2個文件構建輸入輸出流,并且使用一個字節數組作為我們內存的緩存器, 然后使用流從f1 中讀出數據到緩存里,在將緩存數據寫到f2里面去.這里的緩存是2MB的字節數組

第2種方法:使用NIO中的管道到管道傳輸

    public static long forTransfer(File f1,File f2) throws Exception{
        long time=new Date().getTime();
        int length=2097152;
        FileInputStream in=new FileInputStream(f1);
        FileOutputStream out=new FileOutputStream(f2);
        FileChannel inC=in.getChannel();
        FileChannel outC=out.getChannel();
        int i=0;
        while(true){
            if(inC.position()==inC.size()){
                inC.close();
                outC.close();
                return new Date().getTime()-time;
            }
            if((inC.size()-inC.position())<20971520)
                length=(int)(inC.size()-inC.position());
            else
                length=20971520;
            inC.transferTo(inC.position(),length,outC);
            inC.position(inC.position()+length);
            i++;
        }
    }
實現方法:在第一種實現方法基礎上對輸入輸出流獲得其管道,然后分批次的從f1的管道中像f2的管道中輸入數據每次輸入的數據最大為2MB

方法3:內存文件景象寫(讀文件沒有使用文件景象,有興趣的可以回去試試,,我就不試了,估計會更快)

    public static long forImage(File f1,File f2) throws Exception{
        long time=new Date().getTime();
        int length=2097152;
        FileInputStream in=new FileInputStream(f1);
        RandomAccessFile out=new RandomAccessFile(f2,"rw");
        FileChannel inC=in.getChannel();
        MappedByteBuffer outC=null;
        MappedByteBuffer inbuffer=null;
        byte[] b=new byte[length];
        while(true){
            if(inC.position()==inC.size()){
                inC.close();
                outC.force();
                out.close();
                return new Date().getTime()-time;
            }
            if((inC.size()-inC.position())<length){
                length=(int)(inC.size()-inC.position());
            }else{
                length=20971520;
            }
            b=new byte[length];
            inbuffer=inC.map(MapMode.READ_ONLY,inC.position(),length);
            inbuffer.load();
            inbuffer.get(b);
            outC=out.getChannel().map(MapMode.READ_WRITE,inC.position(),length);
            inC.position(b.length+inC.position());
            outC.put(b);
            outC.force();
        }
    }
實現方法:跟傷2個例子不一樣,這里寫文件流沒有使用管道而是使用內存文件映射(假設文件f2在內存中).在循環中從f1的管道中讀取數據到字節數組里,然后在像內存映射的f2文件中寫數據.

第4種方法:管道對管道

    public static long forChannel(File f1,File f2) throws Exception{
        long time=new Date().getTime();
        int length=2097152;
        FileInputStream in=new FileInputStream(f1);
        FileOutputStream out=new FileOutputStream(f2);
        FileChannel inC=in.getChannel();
        FileChannel outC=out.getChannel();
        ByteBuffer b=null;
        while(true){
            if(inC.position()==inC.size()){
                inC.close();
                outC.close();
                return new Date().getTime()-time;
            }
            if((inC.size()-inC.position())<length){
                length=(int)(inC.size()-inC.position());
            }else
                length=2097152;
            b=ByteBuffer.allocateDirect(length);
            inC.read(b);
            b.flip();
            outC.write(b);
            outC.force(false);
        }
    }
這里實現方式與第3種實現方式很類似,不過沒有使用內存影射。



飛熊 2009-10-24 00:41 發表評論
]]>
主站蜘蛛池模板: 平远县| 唐海县| 商水县| 扎赉特旗| 青田县| 靖安县| 外汇| 莱阳市| 共和县| 东港市| 霍邱县| 南昌县| 菏泽市| 习水县| 临洮县| 达拉特旗| 调兵山市| 石景山区| 临城县| 扎兰屯市| 安西县| 常宁市| 汕尾市| 定陶县| 融水| 青川县| 深州市| 常宁市| 哈密市| 三门峡市| 阿鲁科尔沁旗| 凤阳县| 保山市| 襄汾县| 来宾市| 瑞丽市| 福海县| 安新县| 体育| 开远市| 浮山县|