Thinking

快乐编程,开心生活
posts - 21, comments - 27, trackbacks - 0, articles - -5
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

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、如果异步提交耗时较长,可在异步提交之前显示等待提示,在回调函数中根据返回值更新提示;
4、在JS中function也是可以作为变量的,所以我们可以在自己封装的框架中预留回调函数供自定义使用,如下面的代码:
 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中可以使用正则表达式来校验数字域、日期域和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.blogjava.net/byterat/archive/2006/12/20/89143.html
  这本电子书是讲解正则表达式的:http://www.blogjava.net/Files/kawaii/RegularExpressions.zip 
6、在JS编码中,如果代码量较大,要注意防止function名称重复,包括直接在页面上编写的和引用外部JS文件的,不然会出现一些莫名奇妙的问题;
7、注意JS代码中的函数返回语句return的使用;
8、尽量把JS代码写在外部公共的文件中,而在页面中引入,好处有:a.函数复用;b.JS文件缓存;c.提供页面解析速度。基于b,我们在修改JS代码后,要看IE的设置是否将原先的JS文件缓存造成问题;
9、对于同一个页面的多个表单提交,我们可以在第一个表单中设置相应的隐藏域,在表单提交之前利用JS脚本把其他表单的数据设置到第一个表单的隐藏域中;
10、对于异步校验的文本框,我们一般设置触发事件为onblur而不是onchange或者onpropertychange,以减少客户端和服务器的交互次数,但应该注意如果这个文本框最初没有获得焦点,那么onblur就不会触发,可以先调用以下onfocus,再调用onblur手动触发;
11、JS中不存在trim()函数,自定义如下:
 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             //将文字中间多个相连的空格变为一个空格
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 阅读(255) | 评论 (0)编辑 收藏

  1. 启动数据库   
  db2start   
  2. 停止数据库   
  db2stop   
  3. 连接数据库   
  db2   connect   to   o_yd   user   db2   using   pwd   
  4. 读数据库管理程序配置   
  db2   get   dbm   cfg   
  5. 写数据库管理程序配置   
  db2   update   dbm   cfg   using   参数名   参数值   
  6. 读数据库的配置   
  db2   connect   to   o_yd   user   db2   using   pwd   
  db2   get   db   cfg   for   o_yd   
  7. 写数据库的配置   
  db2   connect   to   o_yd   user   db2   using   pwd   
  db2   update   db   cfg   for   o_yd   using   参数名   参数值   
  8. 关闭所有应用连接   
  db2   force   application   all   
  db2   force   application   ID1,ID2,,,Idn   MODE   ASYNC   
  (db2   list   application   for   db   o_yd   show   detail)   
  9. 备份数据库   
  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. 恢复数据库   
  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. 导出表数据  
  db2   export   to   c:\sw.txt   of   del   select   *   from   dftz  
  db2   export   to   c:\sw.ixf   of   ixf   select   *   from   dftz  
  14. 导入表数据  
  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. 执行一个批处理文件  
  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 阅读(239) | 评论 (0)编辑 收藏

1.在应用程序中使用日志的三个目的:
应用程序中添加日志的三个目的:监视代码中变量的变化情况,周期性的记录到文件中供其他应用进行统计分析工作;
跟踪代码运行时轨迹,作为日后审计的依据;
担当集成开发环境中的调试器的作用,向文件或控制台打印代码的调试信息。

2.log4j由三个重要的组件构成:日志信息的优先级,日志信息的输出目的地,日志信息的输出格式。
使用Java特性文件做为配置文件的方法:
2.1. 配置根Logger,其语法为:
log4j.rootLogger = [ level ] , appenderName, appenderName, ...
其中,level 是日志记录的优先级,分为OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL或者您定义的级别。
Log4j建议只使用四个级别,优先级从高到低分别是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(每天产生一个日志文件),
org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件),
org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方)

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(包含日志产生的时间、线程、类别等等信息)

3.在代码中使用Log4j,下面将讲述在程序代码中怎样使用Log4j。

3.1.得到记录器
使用Log4j,第一步就是获取日志记录器,这个记录器将负责控制日志信息。其语法为:
public static Logger getLogger( String name),
通过指定的名字获得记录器,如果必要的话,则为这个名字创建一个新的记录器。Name一般取本类的名字,比如:
static Logger logger = Logger.getLogger ( ServerWithLog4j.class.getName () ) ;

3.2.读取配置文件
当获得了日志记录器之后,第二步将配置Log4j环境,其语法为:
BasicConfigurator.configure (): 自动快速地使用缺省Log4j环境。
PropertyConfigurator.configure ( String configFilename) :读取使用Java的特性文件编写的配置文件。
DOMConfigurator.configure ( String filename ) :读取XML形式的配置文件。

3.3.插入记录信息(格式化日志信息)
当上两个必要步骤执行完毕,您就可以轻松地使用不同优先级别的日志记录语句插入到您想记录日志的任何地方,其语法如下:
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 阅读(255) | 评论 (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发送到客户端,Servlet先要调用new Cookie(name,value)用合适的名字和值创建一个或多个Cookie,通过cookie.setXXX设置各种属性,通过response.addCookie(cookie)把cookie加入 应答头。
   b.要从客户端读入Cookie,Servlet应该调用request.getCookies (),getCookies()方法返回一个Cookie对象的数组。在大多数情况下,你只需要用循环访问该数组的各个元素寻找指定名字的Cookie, 然后对该Cookie调用getValue方法取得与指定名字关联的值。 
   c.创建Cookie 
   调用Cookie对象的构造函数可以创建Cookie。Cookie对象的构造函数有两个字符串参数:Cookie名字和Cookie值。名字和值都不能包含空白字符以及下列字符: 
   [ ] ( ) = , " / ? @ : ;   
   d.读取和设置Cookie属性 
   把Cookie加入待发送的应答头之前,你可以查看或设置Cookie的各种属性。下面摘要介绍这些方法: 
   getComment/setComment 
   获取/设置Cookie的注释。 
   getDomain/setDomain 
   获取/设置Cookie适用的域。一般地,Cookie只返回给与发送它的服务器名字完全相同的服务器。使用这里的方法可以指示浏览器把Cookie返回 给同一域内的其他服务器。注意域必须以点开始(例如.sitename.com),非国家类的域(如.com,.edu,.gov)必须包含两个点,国家 类的域(如.com.cn,.edu.uk)必须包含三个点。 
   getMaxAge/setMaxAge 
   获取/设置Cookie过期之前的时间,以秒计。如果不设置该值,则Cookie只在当前会话内有效,即在用户关闭浏览器之前有效,而且这些Cookie不会保存到磁盘上。参见下面有关LongLivedCookie的说明。 
   getName/setName 
   获取/设置Cookie的名字。本质上,名字和值是我们始终关心的两个部分。由于HttpServletRequest的getCookies方法返回的 是一个Cookie对象的数组,因此通常要用循环来访问这个数组查找特定名字,然后用getValue检查它的值。 
   getPath/setPath 
   获取/设置Cookie适用的路径。如果不指定路径,Cookie将返回给当前页面所在目录及其子目录下的所有页面。这里的方法可以用来设定一些更一般的 条件。例如,someCookie.setPath("/"),此时服务器上的所有页面都可以接收到该Cookie。 
   getSecure/setSecure 
   获取/设置一个boolean值,该值表示是否Cookie只能通过加密的连接(即SSL)发送。 
   getValue/setValue 
   获取/设置Cookie的值。如前所述,名字和值实际上是我们始终关心的两个方面。不过也有一些例外情况,比如把名字作为逻辑标记(也就是说,如果名字存在,则表示true)。 
   getVersion/setVersion 
   获取/设置Cookie所遵从的协议版本。默认版本0(遵从原先的Netscape规范);版本1遵从RFC 2109 , 但尚未得到广泛的支持。 
   e.在应答头中设置Cookie 
   Cookie可以通过HttpServletResponse的addCookie方法加入到Set-Cookie应答头。下面是一个例子: 
1    Cookie userCookie = new Cookie("user""uid1234"); 
2    response.addCookie(userCookie); 

   f.读取保存到客户端的Cookie 
   要把Cookie发送到客户端,先要创建Cookie,然后用addCookie发送一个Set-Cookie HTTP应答头。这些内容已经在上 面的2.1节介绍。从客户端读取Cookie时调用的是HttpServletRequest的getCookies方法。该方法返回一个与HTTP请求 头中的内容对应的Cookie对象数组。得到这个数组之后,一般是用循环访问其中的各个元素,调用getName检查各个Cookie的名字,直至找到目 标Cookie。然后对这个目标Cookie调用getValue,根据获得的结果进行其他处理。 
   上述处理过程经常会 遇到,为方便计下面我们提供一个getCookieValue方法。只要给出Cookie对象数组、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 阅读(170) | 评论 (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运行环境无关的Session集合:
Map sessionMap = ActionContext.getContext().getSession();
    IOC方式访问,可以通过实现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 阅读(566) | 评论 (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  //启动监听线程
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 阅读(1406) | 评论 (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 阅读(379) | 评论 (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 阅读(141) | 评论 (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 阅读(1444) | 评论 (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 阅读(205) | 评论 (0)编辑 收藏