<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    Thinking

    快樂編程,開心生活
    posts - 21, comments - 27, trackbacks - 0, articles - -5
      BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

    2007年2月8日

    CCP Review-Javascript
    1、對于div中的input標簽,如果div的style.display屬性為'none',那么調用input標簽的focus方法在IE6.0上會報錯,首先應該讓其display屬性為''或者'block'再調用;
    2、當HTML元素的name屬性唯一時可以利用document.getElementById()調用獲得這個元素;
    3、如果異步提交耗時較長,可在異步提交之前顯示等待提示,在回調函數(shù)中根據(jù)返回值更新提示;
    4、在JS中function也是可以作為變量的,所以我們可以在自己封裝的框架中預留回調函數(shù)供自定義使用,如下面的代碼:
     1 //common.js
     2 var callback = null;
     3 function commonUse(){
     4   
     5   if(typeof(callback) == "function"){
     6     callback();
     7   }
     8   
     9 }
    10 
    11 //self.js
    12 function selfUse(){
    13   
    14   callback = function(){
    15     //do something before
    16   }
    17   commonUse();
    18   
    19 }

    5、JS中可以使用正則表達式來校驗數(shù)字域、日期域和EMail等。代碼示例如下:
    校驗日期的例子:
     1     function isDate(date){
     2         //對日期格式進行驗證 要求為2000-2099年  格式為 yyyy-mm-dd 并且可以正常轉換成正確的日期
     3         var regex=/^(19|20)\d{2}-((0[1-9]{1})|(1[0-2]{1}))-((0[1-9]{1})|([1-2]{1}[0-9]{1})|(3[0-1]{1}))$/;
     4         
     5         if(!regex.test(date)){
     6             return false;
     7         }
     8         var arr_=date.split("-");
     9         var tmp = new Date(arr_[0], parseFloat(arr_[1])-1, parseFloat(arr_[2]));
    10         if(tmp.getFullYear()!=parseFloat(arr_[0]) 
    11             || tmp.getMonth()!=parseFloat(arr_[1])-1 
    12             || tmp.getDate()!=parseFloat(arr_[2])){
    13             return false;
    14         }
    15          
    16          return true;
    17     }
      這篇文章有詳細的說明:http://www.tkk7.com/byterat/archive/2006/12/20/89143.html
      這本電子書是講解正則表達式的:http://www.tkk7.com/Files/kawaii/RegularExpressions.zip 
    6、在JS編碼中,如果代碼量較大,要注意防止function名稱重復,包括直接在頁面上編寫的和引用外部JS文件的,不然會出現(xiàn)一些莫名奇妙的問題;
    7、注意JS代碼中的函數(shù)返回語句return的使用;
    8、盡量把JS代碼寫在外部公共的文件中,而在頁面中引入,好處有:a.函數(shù)復用;b.JS文件緩存;c.提供頁面解析速度。基于b,我們在修改JS代碼后,要看IE的設置是否將原先的JS文件緩存造成問題;
    9、對于同一個頁面的多個表單提交,我們可以在第一個表單中設置相應的隱藏域,在表單提交之前利用JS腳本把其他表單的數(shù)據(jù)設置到第一個表單的隱藏域中;
    10、對于異步校驗的文本框,我們一般設置觸發(fā)事件為onblur而不是onchange或者onpropertychange,以減少客戶端和服務器的交互次數(shù),但應該注意如果這個文本框最初沒有獲得焦點,那么onblur就不會觸發(fā),可以先調用以下onfocus,再調用onblur手動觸發(fā);
    11、JS中不存在trim()函數(shù),自定義如下:
     1 //JS去除首尾空格(同VBS的Trim)
     2     function trim(inputString) {   
     3         if (typeof inputString != "string") {
     4             return inputString; 
     5         }
     6         var retValue = inputString;
     7         var ch = retValue.substring(01);
     8         while (ch == " ") {
     9                //檢查字符串開始部分的空格
    10             retValue = retValue.substring(1, retValue.length);
    11             ch = retValue.substring(01);
    12         }
    13         ch = retValue.substring(retValue.length-1, retValue.length);
    14         while (ch == " ") {
    15             //檢查字符串結束部分的空格
    16             retValue = retValue.substring(0, retValue.length-1);
    17             ch = retValue.substring(retValue.length-1, retValue.length);
    18         }
    19         while (retValue.indexOf("  "!= -1) {
    20             //將文字中間多個相連的空格變?yōu)橐粋€空格
    21             retValue = retValue.substring(0, retValue.indexOf("  ")) 
    22                 + retValue.substring(retValue.indexOf("  ")+1, retValue.length);
    23         }
    24         return retValue;
    25     }
    12、JS中顯示模式窗口,代碼如下:
     1 function showMyDialog(){
     2   var dialogProperty = 'dialogWidth:800px;dialogHeight:600px;status:no';
     3   var windowProperty = "height=800,width=800,status=no,toolbar=no,menubar=yes,location=yes,resizable=yes,scrollbars=yes";
     4 
     5   var url = "SomeAction.do?id="+id+"&flag=true";
     6   var returnVal = window.showModalDialog(url,"", dialogProperty);
     7   if(typeof(returnVal) == "undefined"){
     8     return;
     9   }
    10   if(returnVal !=  ""){
    11     //do something   
    12   }
    13 }
    14 
    在新打開的模式窗口中,我們通過window.returnValue設置返回值,然后在父頁面中我們通過returnVal可以拿到返回值。

    posted @ 2007-11-27 23:41 lixw 閱讀(280) | 評論 (0)編輯 收藏

      1. 啟動數(shù)據(jù)庫   
      db2start   
      2. 停止數(shù)據(jù)庫   
      db2stop   
      3. 連接數(shù)據(jù)庫   
      db2   connect   to   o_yd   user   db2   using   pwd   
      4. 讀數(shù)據(jù)庫管理程序配置   
      db2   get   dbm   cfg   
      5. 寫數(shù)據(jù)庫管理程序配置   
      db2   update   dbm   cfg   using   參數(shù)名   參數(shù)值   
      6. 讀數(shù)據(jù)庫的配置   
      db2   connect   to   o_yd   user   db2   using   pwd   
      db2   get   db   cfg   for   o_yd   
      7. 寫數(shù)據(jù)庫的配置   
      db2   connect   to   o_yd   user   db2   using   pwd   
      db2   update   db   cfg   for   o_yd   using   參數(shù)名   參數(shù)值   
      8. 關閉所有應用連接   
      db2   force   application   all   
      db2   force   application   ID1,ID2,,,Idn   MODE   ASYNC   
      (db2   list   application   for   db   o_yd   show   detail)   
      9. 備份數(shù)據(jù)庫   
      db2   force   application   all   
      db2   backup   db   o_yd   to   d:   
      (db2   initialize   tape   on   \\.\tape0)   
      (db2   rewind   tape   on   \\.\tape0)   
      db2   backup   db   o_yd   to   \\.\tape0   
      10. 恢復數(shù)據(jù)庫   
      db2   restore   db   o_yd   from   d:   to   d:     
      db2   restore   db   o_yd   from   \\.\tape0   to   d:   
      11. 綁定存儲過程   
      db2   connect   to   o_yd   user   db2   using   pwd   
      db2   bind   c:\dfplus.bnd   
      拷貝存儲過程到服務器上的C:\sqllib\function目錄中   
      12. 整理表   
      db2   connect   to   o_yd   user   db2   using   pwd   
      db2   reorg   table   ydd   
      db2   runstats   on   table   ydd   with   distribution   and   indexes   all     
      13. 導出表數(shù)據(jù)  
      db2   export   to   c:\sw.txt   of   del   select   *   from   dftz  
      db2   export   to   c:\sw.ixf   of   ixf   select   *   from   dftz  
      14. 導入表數(shù)據(jù)  
      db2   import   from   c:\sw.txt   of   del   insert   into   ylbx.czyxx  
      db2   import   to   c:\sw.txt   of   del   commitcount   5000   messages       c:\dftz.msg   insert   into   dftz  
      db2   import   to   c:\dftz.ixf   of   ixf   commitcount   5000   messages   c:\dftz.msg   insert   into   dftz  
      db2   import   to   c:\dftz.ixf   of   ixf   commitcount   5000   insert   into   dftz  
      db2   import   to   c:\dftz.ixf   of   ixf   commitcount   5000   insert_update   into   dftz  
      db2   import   to   c:\dftz.ixf   of   ixf   commitcount   5000   replace   into   dftz  
      db2   import   to   c:\dftz.ixf   of   ixf   commitcount   5000   create   into   dftz       (僅IXF)  
      db2   import   to   c:\dftz.ixf   of   ixf   commitcount   5000   replace_create   into   dftz     (僅IXF)  
      15. 執(zhí)行一個批處理文件  
      db2   –tf   批處理文件名  
      (文件中每一條命令用   ;結束)  
      16. 自動生成批處理文件  
      建文本文件:temp.sql  
      select   'runstats   on   table   DB2.'   ||   tabname   ||   '   with   distribution   and   detailed   indexes   all;'   from   syscat.tables   where   tabschema='DB2'   and   type='T';
      db2   –tf   temp.sql>runstats.sql  
      17. 自動生成建表(視圖)語句  
      在服務器上:C:\sqllib\misc目錄中  
      db2   connect   to   o_yd   user   db2   using   pwd  
      db2look   –d   o_yd   –u   db2   –e   –p   –c   c:\o_yd.txt     
      db2look   -d   lys   -e   -a   -x   -i   db2admin   -o   c:\aa.txt  
      18. 其他命令  
      grant   dbadm   on   database   to   user   bb   
      19.    select   *   from   czyxx   fetch   first   1   rows   only  
      20.    db2look   –d   lys   –u   db2admin   –w   –asd   –a   –e   –o   c:\mytable.txt   

    posted @ 2007-04-27 08:54 lixw 閱讀(263) | 評論 (0)編輯 收藏

    1.在應用程序中使用日志的三個目的:
    應用程序中添加日志的三個目的:監(jiān)視代碼中變量的變化情況,周期性的記錄到文件中供其他應用進行統(tǒng)計分析工作;
    跟蹤代碼運行時軌跡,作為日后審計的依據(jù);
    擔當集成開發(fā)環(huán)境中的調試器的作用,向文件或控制臺打印代碼的調試信息。

    2.log4j由三個重要的組件構成:日志信息的優(yōu)先級,日志信息的輸出目的地,日志信息的輸出格式。
    使用Java特性文件做為配置文件的方法:
    2.1. 配置根Logger,其語法為:
    log4j.rootLogger = [ level ] , appenderName, appenderName, ...
    其中,level 是日志記錄的優(yōu)先級,分為OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL或者您定義的級別。
    Log4j建議只使用四個級別,優(yōu)先級從高到低分別是ERROR、WARN、INFO、DEBUG。
    通過在這里定義的級別,您可以控制到應用程序中相應級別的日志信息的開關。
    比如在這里定義了INFO級別,則應用程序中所有DEBUG級別的日志信息將不被打印出來。
    appenderName就是指定日志信息輸出到哪個地方。您可以同時指定多個輸出目的地。
    2.2. 配置日志信息輸出目的地Appender,其語法為
    log4j.appender.appenderName = fully.qualified.name.of.appender.class
    log4j.appender.appenderName.option1 = value1
    ...
    log4j.appender.appenderName.option = valueN

    其中,Log4j提供的appender有以下幾種:
    org.apache.log4j.ConsoleAppender(控制臺),
    org.apache.log4j.FileAppender(文件),
    org.apache.log4j.DailyRollingFileAppender(每天產(chǎn)生一個日志文件),
    org.apache.log4j.RollingFileAppender(文件大小到達指定尺寸的時候產(chǎn)生一個新的文件),
    org.apache.log4j.WriterAppender(將日志信息以流格式發(fā)送到任意指定的地方)

    2.3. 配置日志信息的格式(布局),其語法為:
    log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class
    log4j.appender.appenderName.layout.option1 = value1
    ...
    log4j.appender.appenderName.layout.option = valueN

    其中,Log4j提供的layout有以下幾種:
    org.apache.log4j.HTMLLayout(以HTML表格形式布局),
    org.apache.log4j.PatternLayout(可以靈活地指定布局模式),
    org.apache.log4j.SimpleLayout(包含日志信息的級別和信息字符串),
    org.apache.log4j.TTCCLayout(包含日志產(chǎn)生的時間、線程、類別等等信息)

    3.在代碼中使用Log4j,下面將講述在程序代碼中怎樣使用Log4j。

    3.1.得到記錄器
    使用Log4j,第一步就是獲取日志記錄器,這個記錄器將負責控制日志信息。其語法為:
    public static Logger getLogger( String name),
    通過指定的名字獲得記錄器,如果必要的話,則為這個名字創(chuàng)建一個新的記錄器。Name一般取本類的名字,比如:
    static Logger logger = Logger.getLogger ( ServerWithLog4j.class.getName () ) ;

    3.2.讀取配置文件
    當獲得了日志記錄器之后,第二步將配置Log4j環(huán)境,其語法為:
    BasicConfigurator.configure (): 自動快速地使用缺省Log4j環(huán)境。
    PropertyConfigurator.configure ( String configFilename) :讀取使用Java的特性文件編寫的配置文件。
    DOMConfigurator.configure ( String filename ) :讀取XML形式的配置文件。

    3.3.插入記錄信息(格式化日志信息)
    當上兩個必要步驟執(zhí)行完畢,您就可以輕松地使用不同優(yōu)先級別的日志記錄語句插入到您想記錄日志的任何地方,其語法如下:
    Logger.debug ( Object message ) ;
    Logger.info ( Object message ) ;
    Logger.warn ( Object message ) ;
    Logger.error ( Object message ) ;

    一個配置的例子:
    log4j.rootLogger=INFO, stdout ,R
    log4j.appender.stdout.Threshold=ERROR
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[QC] %p [%t] %C.%M(%L) | %m%n log4j.appender.R.Threshold=INFO
    log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.R.File=c:/log.log
    log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n

    posted @ 2007-04-25 17:34 lixw 閱讀(278) | 評論 (0)編輯 收藏


    1、在Javascript中操作Cookie:
    ?1?<script>
    ?2?//設置Cookie
    ?3???function?setCookie(va){
    ?4????????var?expires?=?new?Date();
    ?5???????expires.setTime(expires.getTime()?+?12?*?30?*?24?*?60?*?60?*?1000);
    ?6???????/*???一年?x?一個月當作?30?天?x?一天?24?小時
    ?7???????x?一小時?60?分?x?一分?60?秒?x?一秒?1000?毫秒?*/
    ?8????????document.cookie=va+';expires='+expires.toGMTString();
    ?9???}
    10???//讀取Cookie
    11???function?readCookie(name){
    12???var?cookieValue?=?"";
    13???var?search?=?name?+?"=";
    14???if(document.cookie.length?>?0)??{
    15?????offset?=?document.cookie.indexOf(search);
    16?????if?(offset?!=?-1)????{
    17???????offset?+=?search.length;
    18???????end?=?document.cookie.indexOf(";",?offset);
    19???????if?(end?==?-1)?end?=?document.cookie.length;
    20???????cookieValue?=?unescape(document.cookie.substring(offset,?end))
    21?????}
    22???}
    23???return?cookieValue;
    24?}
    25?
    26?setCookie("user=123");
    27?alert(readCookie('user'));
    28?</script>
    2、在Servlet中操作Cookie:
    ?? a.要把Cookie發(fā)送到客戶端,Servlet先要調用new?Cookie(name,value)用合適的名字和值創(chuàng)建一個或多個Cookie,通過cookie.setXXX設置各種屬性,通過response.addCookie(cookie)把cookie加入 應答頭。
    ?? b.要從客戶端讀入Cookie,Servlet應該調用request.getCookies (),getCookies()方法返回一個Cookie對象的數(shù)組。在大多數(shù)情況下,你只需要用循環(huán)訪問該數(shù)組的各個元素尋找指定名字的Cookie, 然后對該Cookie調用getValue方法取得與指定名字關聯(lián)的值。?
    ?? c.創(chuàng)建Cookie?
    ?? 調用Cookie對象的構造函數(shù)可以創(chuàng)建Cookie。Cookie對象的構造函數(shù)有兩個字符串參數(shù):Cookie名字和Cookie值。名字和值都不能包含空白字符以及下列字符:?
    ???[?]?(?)?=?,?"?/???@?:?;? ?
    ?? d.讀取和設置Cookie屬性?
    ?? 把Cookie加入待發(fā)送的應答頭之前,你可以查看或設置Cookie的各種屬性。下面摘要介紹這些方法:?
    ?? getComment/setComment?
    ?? 獲取/設置Cookie的注釋。?
    ?? getDomain/setDomain?
    ?? 獲取/設置Cookie適用的域。一般地,Cookie只返回給與發(fā)送它的服務器名字完全相同的服務器。使用這里的方法可以指示瀏覽器把Cookie返回 給同一域內的其他服務器。注意域必須以點開始(例如.sitename.com),非國家類的域(如.com,.edu,.gov)必須包含兩個點,國家 類的域(如.com.cn,.edu.uk)必須包含三個點。?
    ?? getMaxAge/setMaxAge?
    ?? 獲取/設置Cookie過期之前的時間,以秒計。如果不設置該值,則Cookie只在當前會話內有效,即在用戶關閉瀏覽器之前有效,而且這些Cookie不會保存到磁盤上。參見下面有關LongLivedCookie的說明。?
    ?? getName/setName?
    ?? 獲取/設置Cookie的名字。本質上,名字和值是我們始終關心的兩個部分。由于HttpServletRequest的getCookies方法返回的 是一個Cookie對象的數(shù)組,因此通常要用循環(huán)來訪問這個數(shù)組查找特定名字,然后用getValue檢查它的值。?
    ?? getPath/setPath?
    ?? 獲取/設置Cookie適用的路徑。如果不指定路徑,Cookie將返回給當前頁面所在目錄及其子目錄下的所有頁面。這里的方法可以用來設定一些更一般的 條件。例如,someCookie.setPath("/"),此時服務器上的所有頁面都可以接收到該Cookie。?
    ?? getSecure/setSecure?
    ?? 獲取/設置一個boolean值,該值表示是否Cookie只能通過加密的連接(即SSL)發(fā)送。?
    ?? getValue/setValue?
    ?? 獲取/設置Cookie的值。如前所述,名字和值實際上是我們始終關心的兩個方面。不過也有一些例外情況,比如把名字作為邏輯標記(也就是說,如果名字存在,則表示true)。?
    ?? getVersion/setVersion?
    ?? 獲取/設置Cookie所遵從的協(xié)議版本。默認版本0(遵從原先的Netscape規(guī)范);版本1遵從RFC?2109?,?但尚未得到廣泛的支持。?
    ?? e.在應答頭中設置Cookie?
    ?? Cookie可以通過HttpServletResponse的addCookie方法加入到Set-Cookie應答頭。下面是一個例子:?
    1????Cookie?userCookie?=?new?Cookie("user",?"uid1234");?
    2????response.addCookie(userCookie);?

    ?? f.讀取保存到客戶端的Cookie?
    ?? 要把Cookie發(fā)送到客戶端,先要創(chuàng)建Cookie,然后用addCookie發(fā)送一個Set-Cookie?HTTP應答頭。這些內容已經(jīng)在上 面的2.1節(jié)介紹。從客戶端讀取Cookie時調用的是HttpServletRequest的getCookies方法。該方法返回一個與HTTP請求 頭中的內容對應的Cookie對象數(shù)組。得到這個數(shù)組之后,一般是用循環(huán)訪問其中的各個元素,調用getName檢查各個Cookie的名字,直至找到目 標Cookie。然后對這個目標Cookie調用getValue,根據(jù)獲得的結果進行其他處理。?
    ?? 上述處理過程經(jīng)常會 遇到,為方便計下面我們提供一個getCookieValue方法。只要給出Cookie對象數(shù)組、Cookie名字和默認值, getCookieValue方法就會返回匹配指定名字的Cookie值,如果找不到指定Cookie,則返回默認值。?

    ?? 獲取指定名字的Cookie值?
    1?public?static?String?getCookieValue(Cookie[]?cookies,?
    2????????String?cookieName,String?defaultValue)?{?
    3????????for(int?i=0;?i<cookies.length;?i++)?{?
    4????????????Cookie?cookie?=?cookies[i];?
    5????????????if?(cookieName.equals(cookie.getName()))?{
    6????????????????return(cookie.getValue());?
    7????????????}?
    8????????return(defaultValue);?
    9????}?


    posted @ 2007-02-27 08:57 lixw 閱讀(183) | 評論 (0)編輯 收藏

    1、在Action中獲得Servlet API中的對象:
    1?com.opensymphony.xwork2.ActionContext?context?=?ActionContext.getContext();
    2?HttpServletRequest?request?=?org.apache.struts2.ServletActionContext.getRequest();
    3?HttpServletResponse?response?=?org.apache.struts2.ServletActionContext.getResponse();
    4?HttpSession?session?=?request.getSession();

    ??? 獲取與Servlet運行環(huán)境無關的Session集合:
    Map?sessionMap?=?ActionContext.getContext().getSession();
    ??? IOC方式訪問,可以通過實現(xiàn)ServletRequestAware、ServletResponseAware和SessionAware。
    參考WebWork API
    2、自定義Action調用方法:
    • 在struts.xml的action配置中,增加屬性method="aliasMethod";
    • 在訪問Action的URL中增加!aliasMethod.action,形如 http://localhost:8080/app/ActionName!aliasMethod.action。
    3、自己布局form:
    ??? 給<s:form />增加屬性theme="simple"。

    4、WebWork中的特殊命名對象:
    ??? #prameters['foo'] or #parameters.foo??????????? ??? request.getParameter("foo");
    ??? #request['foo'] or #request.foo?? ?? ?? ?? ?? ?? ?? request.getAttribute("foo");
    ??? #session['foo'] or #session.foo?? ?? ?? ?? ?? ?? ?? session.getAttribute("foo");
    ??? #application['foo'] or #application.foo?? ?? ?? ??? application.getAttribute("foo");
    ??? #attr['foo'] or #attr.foo?? ?? ?? ?? ?? ?? ?? ?? ?? pageContext.getAttribute("foo");
    ??

    posted @ 2007-02-26 10:23 lixw 閱讀(603) | 評論 (2)編輯 收藏

    一種比較簡陋的方法:

    ?1?ActionListener?taskPerformer?=?new?ActionListener()?{
    ?2?????????????public?void?actionPerformed(ActionEvent?evt)?{
    ?3?????????????????log.info("monitor?is?running?at?"?+?new?java.util.Date());
    ?4?????????????????String?configfile?=?(String)getServletContext().getAttribute("configfile");
    ?5?????????????????if(configfile?!=?null?&&?configfile.length()!=0){
    ?6?????????????????????try{
    ?7?????????????????????????File?file?=?new?File(configfile);
    ?8?????????????????????????if(file.lastModified()?>?lastModifyTime){
    ?9?????????????????????????????lastModifyTime?=?file.lastModified();
    10?????????????????????????????loadProp();
    11?????????????????????????}
    12?????????????????????}catch(Exception?e){
    13?????????????????????????log.error("construct?file:"?+?configfile?+?"?exception");
    14?????????????????????????e.printStackTrace();
    15?????????????????????}
    16?????????????????}
    17?????????????}
    18? };
    19?????????
    20? //啟動監(jiān)聽線程
    21?new?Timer(delay,?taskPerformer).start();


    來自geosoft.no的解決方法:
    ?1?import?java.io.File;
    ?2?
    ?3?/**
    ?4??*?Interface?for?listening?to?disk?file?changes.
    ?5??*?@see?FileMonitor
    ?6??*?
    ?7??*?@author?<a?href="mailto:jacob.dreyer@geosoft.no">Jacob?Dreyer</a>
    ?8??*/???
    ?9?public?interface?FileListener
    10?{
    11???/**
    12????*?Called?when?one?of?the?monitored?files?are?created,?deleted
    13????*?or?modified.
    14????*?
    15????*?@param?file??File?which?has?been?changed.
    16????*/
    17???void?fileChanged?(File?file);
    18?}

    ??1?import?java.util.*;
    ??2?import?java.io.File;
    ??3?import?java.lang.ref.WeakReference;
    ??4?
    ??5?/**
    ??6??*?Class?for?monitoring?changes?in?disk?files.
    ??7??*?Usage:
    ??8??*
    ??9??*????1.?Implement?the?FileListener?interface.
    ?10??*????2.?Create?a?FileMonitor?instance.
    ?11??*????3.?Add?the?file(s)/directory(ies)?to?listen?for.
    ?12??*
    ?13??*?fileChanged()?will?be?called?when?a?monitored?file?is?created,
    ?14??*?deleted?or?its?modified?time?changes.
    ?15??*
    ?16??*?@author?<a?href="mailto:jacob.dreyer@geosoft.no">Jacob?Dreyer</a>
    ?17??*/???
    ?18?public?class?FileMonitor
    ?19?{
    ?20???private?Timer???????timer_;
    ?21???private?HashMap?????files_;???????//?File?->?Long
    ?22???private?Collection??listeners_;???//?of?WeakReference(FileListener)
    ?23????
    ?24?
    ?25???/**
    ?26????*?Create?a?file?monitor?instance?with?specified?polling?interval.
    ?27????*?
    ?28????*?@param?pollingInterval??Polling?interval?in?milli?seconds.
    ?29????*/
    ?30???public?FileMonitor?(long?pollingInterval)
    ?31???{
    ?32?????files_?????=?new?HashMap();
    ?33?????listeners_?=?new?ArrayList();
    ?34?
    ?35?????timer_?=?new?Timer?(true);
    ?36?????timer_.schedule?(new?FileMonitorNotifier(),?0,?pollingInterval);
    ?37???}
    ?38?
    ?39?
    ?40???
    ?41???/**
    ?42????*?Stop?the?file?monitor?polling.
    ?43????*/
    ?44???public?void?stop()
    ?45???{
    ?46?????timer_.cancel();
    ?47???}
    ?48???
    ?49?
    ?50???/**
    ?51????*?Add?file?to?listen?for.?File?may?be?any?java.io.File?(including?a
    ?52????*?directory)?and?may?well?be?a?non-existing?file?in?the?case?where?the
    ?53????*?creating?of?the?file?is?to?be?trepped.
    ?54????*?<p>
    ?55????*?More?than?one?file?can?be?listened?for.?When?the?specified?file?is
    ?56????*?created,?modified?or?deleted,?listeners?are?notified.
    ?57????*?
    ?58????*?@param?file??File?to?listen?for.
    ?59????*/
    ?60???public?void?addFile?(File?file)
    ?61???{
    ?62?????if?(!files_.containsKey?(file))?{
    ?63???????long?modifiedTime?=?file.exists()???file.lastModified()?:?-1;
    ?64???????files_.put?(file,?new?Long?(modifiedTime));
    ?65?????}
    ?66???}
    ?67?
    ?68???
    ?69?
    ?70???/**
    ?71????*?Remove?specified?file?for?listening.
    ?72????*?
    ?73????*?@param?file??File?to?remove.
    ?74????*/
    ?75???public?void?removeFile?(File?file)
    ?76???{
    ?77?????files_.remove?(file);
    ?78???}
    ?79?
    ?80?
    ?81???
    ?82???/**
    ?83????*?Add?listener?to?this?file?monitor.
    ?84????*?
    ?85????*?@param?fileListener??Listener?to?add.
    ?86????*/
    ?87???public?void?addListener?(FileListener?fileListener)
    ?88???{
    ?89?????//?Don't?add?if?its?already?there
    ?90?????for?(Iterator?i?=?listeners_.iterator();?i.hasNext();?)?{
    ?91???????WeakReference?reference?=?(WeakReference)?i.next();
    ?92???????FileListener?listener?=?(FileListener)?reference.get();
    ?93???????if?(listener?==?fileListener)
    ?94?????????return;
    ?95?????}
    ?96?
    ?97?????//?Use?WeakReference?to?avoid?memory?leak?if?this?becomes?the
    ?98?????//?sole?reference?to?the?object.
    ?99?????listeners_.add?(new?WeakReference?(fileListener));
    100???}
    101?
    102?
    103???
    104???/**
    105????*?Remove?listener?from?this?file?monitor.
    106????*?
    107????*?@param?fileListener??Listener?to?remove.
    108????*/
    109???public?void?removeListener?(FileListener?fileListener)
    110???{
    111?????for?(Iterator?i?=?listeners_.iterator();?i.hasNext();?)?{
    112???????WeakReference?reference?=?(WeakReference)?i.next();
    113???????FileListener?listener?=?(FileListener)?reference.get();
    114???????if?(listener?==?fileListener)?{
    115?????????i.remove();
    116?????????break;
    117???????}
    118?????}
    119???}
    120?
    121?
    122???
    123???/**
    124????*?This?is?the?timer?thread?which?is?executed?every?n?milliseconds
    125????*?according?to?the?setting?of?the?file?monitor.?It?investigates?the
    126????*?file?in?question?and?notify?listeners?if?changed.
    127????*/
    128???private?class?FileMonitorNotifier?extends?TimerTask
    129???{
    130?????public?void?run()
    131?????{
    132???????//?Loop?over?the?registered?files?and?see?which?have?changed.
    133???????//?Use?a?copy?of?the?list?in?case?listener?wants?to?alter?the
    134???????//?list?within?its?fileChanged?method.
    135???????Collection?files?=?new?ArrayList?(files_.keySet());
    136???????
    137???????for?(Iterator?i?=?files.iterator();?i.hasNext();?)?{
    138?????????File?file?=?(File)?i.next();
    139?????????long?lastModifiedTime?=?((Long)?files_.get?(file)).longValue();
    140?????????long?newModifiedTime??=?file.exists()???file.lastModified()?:?-1;
    141?
    142?????????//?Chek?if?file?has?changed
    143?????????if?(newModifiedTime?!=?lastModifiedTime)?{
    144?
    145???????????//?Register?new?modified?time
    146???????????files_.put?(file,?new?Long?(newModifiedTime));
    147?
    148???????????//?Notify?listeners
    149???????????for?(Iterator?j?=?listeners_.iterator();?j.hasNext();?)?{
    150?????????????WeakReference?reference?=?(WeakReference)?j.next();
    151?????????????FileListener?listener?=?(FileListener)?reference.get();
    152?
    153?????????????//?Remove?from?list?if?the?back-end?object?has?been?GC'd
    154?????????????if?(listener?==?null)
    155???????????????j.remove();
    156?????????????else
    157???????????????listener.fileChanged?(file);
    158???????????}
    159?????????}
    160???????}
    161?????}
    162???}
    163?
    164?
    165???/**
    166????*?Test?this?class.
    167????*?
    168????*?@param?args??Not?used.
    169????*/
    170???public?static?void?main?(String?args[])
    171???{
    172?????//?Create?the?monitor
    173?????FileMonitor?monitor?=?new?FileMonitor?(1000);
    174?
    175?????//?Add?some?files?to?listen?for
    176?????monitor.addFile?(new?File?("D:\\myjava\\JCreatorWorkspace\\FileMonitor\\test.txt"));
    177?
    178?????//?Add?a?dummy?listener
    179?????monitor.addListener?(monitor.new?TestListener());
    180?
    181?????//?Avoid?program?exit
    182?????while?(!false)?;
    183???}
    184?
    185???
    186???private?class?TestListener
    187?????implements?FileListener
    188???{
    189?????public?void?fileChanged?(File?file)
    190?????{
    191???????System.out.println?("File?["?+?file.getName()?+?"]?changed?At:"?+?new?java.util.Date());
    192?????}
    193???}
    194?}
    195?
    196?
    197?

    posted @ 2007-02-08 10:07 lixw 閱讀(1432) | 評論 (2)編輯 收藏


    1?//file?may?be?named?basename_locale.properties
    2?ResourceBundle?bundle?=?ResourceBundle.getBundle("basename");
    3?//?Enumerate?contents?of?resource?bundle
    4?//The?next?two?lines?should?be?in?one?line.
    5?for?(Enumeration?props?=?bundle.getKeys();props.hasMoreElements();?)?{
    6?????String?key?=?(String)props.nextElement();
    7?????process(key,?bundle.getObject(key));
    8?}

    posted @ 2007-02-08 09:43 lixw 閱讀(403) | 評論 (0)編輯 收藏


    1?String?aString?=?"word1?word2?word3";
    2?StringTokenizer?parser?=?new?StringTokenizer(aString);
    3?while?(parser.hasMoreTokens())?{
    4?????processWord(parser.nextToken());
    5?}

    posted @ 2007-02-08 09:43 lixw 閱讀(153) | 評論 (0)編輯 收藏


    ?1?public?static?long?checksum(byte[]?buf)?{
    ?2?????try?{
    ?3?????????CheckedInputStream?cis?=?new?CheckedInputStream(
    ?4????????new?ByteArrayInputStream(buf),new?Adler32());
    ?5?????????byte[]?tempBuf?=?new?byte[128];
    ?6?????????while?(cis.read(tempBuf)?>=?0);????????return?cis.getChecksum().getValue();
    ?7?????}?catch?(IOException?e)?{
    ?8?????????return?-1;
    ?9?????}
    10?}

    posted @ 2007-02-08 09:41 lixw 閱讀(1469) | 評論 (0)編輯 收藏

    ?1?try?{
    ?2??????String?inFilename?=?"infile";
    ?3??????String?outFilename?=?"outfile.zip";
    ?4??????FileInputStream?in?=?new?FileInputStream(inFilename);
    ?5??????ZipOutputStream?out?=?new?ZipOutputStream(new?FileOutputStream(outFilename));
    ?6???????????//?Add?ZIP?entry?to?output?stream.
    ?7??????out.putNextEntry(new?ZipEntry(inFilename));
    ?8??????byte[]?buf?=?new?byte[1024];
    ?9??????int?len;
    10??????while?((len?=?in.read(buf))?>?0)?{
    11??????????out.write(buf,?0,?len);
    12?????}
    13?????????out.closeEntry();
    14?????out.close();
    15?????in.close();
    16?}catch?(IOException?e)?{}



    ?1?try?{
    ?2??????String?inFilename?=?"infile.zip";
    ?3??????String?outFilename?=?"outfile";
    ?4??????ZipInputStream?in?=?new?ZipInputStream(new?FileInputStream(inFilename));
    ?5??????OutputStream?out?=?new?FileOutputStream(outFilename);
    ?6??????ZipEntry?entry;
    ?7??????byte[]?buf?=?new?byte[1024];
    ?8??????int?len;
    ?9??????if?((entry?=?in.getNextEntry())?!=?null)?{
    10??????????while?((len?=?in.read(buf))?>?0)?{
    11???????????????out.write(buf,?0,?len);
    12??????????}
    13??????}
    14??????out.close();
    15??????in.close();
    16??}?catch?(IOException?e)?{
    17??}

    posted @ 2007-02-08 09:35 lixw 閱讀(214) | 評論 (0)編輯 收藏

    主站蜘蛛池模板: 亚洲永久在线观看| 一级黄色免费毛片| 亚洲毛片在线免费观看| 拔擦拔擦8x华人免费久久| 无人在线观看完整免费版视频| 国产精品久久久久久久久免费| 亚洲免费观看网站| 在线视频精品免费| 国产情侣激情在线视频免费看| 国产又大又粗又长免费视频 | 国产精品亚洲专区在线观看| 久久亚洲AV成人无码| 免费人成在线观看播放国产 | 日韩免费在线视频| 三年片在线观看免费大全电影 | 久久久久女教师免费一区| 波霸在线精品视频免费观看| 中国一级毛片视频免费看| 国产成人精品一区二区三区免费| 99热精品在线免费观看| 在线观看H网址免费入口| 精品剧情v国产在免费线观看| 四虎影视精品永久免费网站| 久久夜色精品国产亚洲av| 久久久无码精品亚洲日韩蜜桃 | 亚洲欧洲精品成人久久奇米网 | 亚洲国产国产综合一区首页| 亚洲视频国产视频| 亚洲夂夂婷婷色拍WW47| www亚洲精品久久久乳| caoporn成人免费公开| 久草视频在线免费看| 97碰公开在线观看免费视频| 天天摸天天碰成人免费视频| 亚洲AV中文无码乱人伦在线视色| 亚洲国产精彩中文乱码AV| 亚洲欧洲日本国产| 亚洲AV成人精品一区二区三区| 一级毛片一级毛片免费毛片| 无码囯产精品一区二区免费| 成年在线网站免费观看无广告|