---
title: "Java Programming Tricks 1"
author: "speed847"
date: "2009-04-27T13:44:05Z"
tags: []
slug: "java-programming-tricks-1"
draft: false
lastmod: "2009-04-27T13:59:49Z"
id: 375482
url: "https://speed847.iteye.com/blog/375482"
---

**1、计算时间**

 

       long StartTime = System.currentTimeMillis(); // 取出目前時間

// ==============================  
// 你的程式  
// ==============================

long ProcessTime = System.currentTimeMillis() - StartTime; // 計算處理時間

 

 

**2、线程休眠**

 

       try {

       Thread.sleep(500);

} catch (InterruptedException e) { }

 

 

**3、生成随机数**

 

       int randomNumber=(int)(Math.random()\*８)+1；

 

 

**4、Runtime.getRuntime( ).exec( ) 的运用**

 

（1）打开本地文件

public class OpenFile {

    public static void main(String\[] args) {

        String path = "c:/temp/SW.txt";

        try{

            Runtime.getRuntime().exec("cmd /c start "+path);

        }catch(Exception e) {

           

        }

    }

}

（2）运行.bat文件

public class RunBat {

    public RunBat (String cmdline) {

        try{

            Process p = Runtime.getRuntime().exec(cmdline);

        }catch(Exception e) {

        }

    }

    public static void main(String\[] args) {

        new RunBat("c:/temp/test.bat");

    }

}

（3）运行exe 文件

public class OpenFile {

    public static void main(String\[] args) {

        try{

            Runtime.getRuntime().exec("c:/temp/WinRAR.exe");

        }catch(Exception e){

        }

    }

}

 

 

 

**5、HashMap 用法**

 

private static final String FUND\_KEY = "fund";

private static final String SUB\_KEY = "subaccount";

 

HashMap resultMap = new HashMap(2);

List mrFunds = new ArrayList();

List mrSubaccts = new ArrayList();

resultMap.put(FUND\_KEY, mrFunds);

resultMap.put(SUB\_KEY, mrSubaccts);

return resultMap;

 

HashMap mrAccts = getSelectedChildrenForMRGroup(groups);

List mrFunds = (List)mrAccts.get(FUND\_KEY);

List mrSubacctouns = (List)mrAccts.get(SUB\_KEY);

 

**6、Log**

 

public void save\_old(AddClient addClient) {

              log.debug("execting AddClient");

              try {

                     getHibernateTemplate().save(addClient);

                     log.debug("AddClient successful");

              } catch (RuntimeException re) {

                     log.error("AddClient failed", re);

                     throw re;

              }

       }