第六章 Java API

           

          第六講 Java API

               理解API的概念

               java輔助工具的使用

               String類和StringBuffer

               基本數據類型的對象包裝類

               集合類

               HashtableProperties

               System類與Runtime

               DateCalendarDateFormat

               TimerTimerTask

               MathRandom

               學習API的方法

          理解API的概念

               API的概念

          (Application Programming Interface)

                

               Window API

          就是Windows操作系統提供的各種函數,例如,CreatWindow

               Java API

          就是JDK中提供的各種Java類,例如,System類。

          Java工具軟件

               Borland公司的Jbuilder

               IBM公司的Visual Age

               Sun公司的Sun ONE Studio

               塞六鐵克的Visual cafe

               Jcreator

               Jcreator Pro

               下載地址:http://www.Jcreator.com

               工作區(jcw)與工程(jcp)

               使用類向導創建新類

               使用動態隨筆功能和自動輸入功能

               指定Jcreator所有使用的JDK

               設置第三方提供的Jar

               指定啟動運行類及參數

               設置多個運行配置環境

          String類和StringBuffer

               位于java.lang包中。

               String類對象中的內容一旦被初始化就不能再改變。

               StringBuffer類用于封閉內容可以改變的字符串。

          toString方法轉換成String類型

          String x=”a”+4+”c”,編譯時等效于:

          String x=new StringBuffer().append(“a”).append(4).append(“c”).toString();

               字符串常量(如”hello”)實際上是一種特殊的匿名String對象。比較下面兩種情況的差異:

               String s1=”hello”; String s2=”hello”;

               String s1=new String(“hello”); String s2=new String(“hello”);

          編程實例:逐行讀取鍵盤輸入,直到輸入內容為”bye”時,結束程序。

           

          public class ReadLine

          {

                 public static void main(String[] args)

                 {

                        int pos=0;

                        int ch=0;

                        byte []buf=new byte [1024];

                        String strInfo=null;

                        System.out.println("請輸入內容:");

                        while(true)

                        {

                               try{ch=System.in.read();}catch(Exception e){e.printStackTrace();}

                               switch(ch)

                               {

                                      case '\r':

                                             break;

                                      case '\n':

                                             strInfo=new String(buf,0,pos);

                                             if(strInfo.equals("bye"))

                                             //if(strInfo.equalsIgnoreCase("bye"))忽略大小寫。

                                             {

                                                    return;

                                             }

                                             else

                                             {

                                                    System.out.println(strInfo);

                                                    pos=0;

                                                    break;

                                             }

                                      default:

                                             buf[pos++]=(byte)ch;

                               }

                        }

                 }    

          }

          String類的常用成員方法

               構造方法:

               String(byte[] bytes, int offset, int length)
                    
          構造一個新的 String,方法是使用指定的字符集解碼字節的指定子數組。

               charAt(int index)
                    
          返回指定索引處的 char

               compareTo(String anotherString)
                    
          按字典順序比較兩個字符串。

               indexOf(int ch)
                    
          返回指定字符在此字符串中第一次出現處的索引。如果不存在這樣的值,則返回 -1

                   例:strName.indexOf(‘a’);

               indexOf(int ch, int fromIndex)
                    
          從指定的索引開始搜索,返回在此字符串中第一次出現指定字符處的索引。

               indexOf(String str)
                    
          返回第一次出現的指定子字符串在此字符串中的索引。

               indexOf(String str, int fromIndex)
                    
          從指定的索引處開始,返回第一次出現的指定子字符串在此字符串中的索引。

               length()
                    
          返回此字符串的長度。

               substring(int beginIndex)
                    
          返回一個新的字符串,它是此字符串的一個子字符串。

               substring(int beginIndex, int endIndex)
                    
          返回一個新字符串,它是此字符串的一個子字符串。

               toLowerCase()
                    
          使用默認語言環境的規則將此 String 中的所有字符都轉換為小寫。

               toUpperCase()
                    
          使用默認語言環境的規則將此 String 中的所有字符都轉換為大寫。

               valueOf(int i)
                    
          返回 int 參數的字符串表示形式。

               ………………………………………………………..

          StringBuffer

          reverse()
                    
          將此字符序列用其反轉形式取代。

                

          基本數據類型的對象包裝類

               基本數據類型包裝類的作用

          基本數據類型

          包裝類

          boolean

          Boolean

          byte

          Byte

          char

          Character

          short

          Short

          Int

          Integer

          Long

          Long

          float

          Float

          double

          Double

           

          編程實例:將字符串轉換成整數的編程舉例

          在屏幕上打印出一個星號(*)組成的矩形,矩形的寬度和高度通過啟動程序時傳遞給main方法的參數指定,并比較下面兩段代碼的運行效率:

          String sb=new String();                      StringBuffer sb=new StringBuffer();

          for(int j=0;j<w;j++)                            for(int j=0;j<w;j++)

          {                                                      {

                 sb=sb+*;                                           sb.append(*);

          }                                                      }

           

          以下黑粗體部分是“字符串轉換成整數”的3種方法。

          public class lesson64

          {

                 public static void main(String[] args)

                 {

                        int h=new Integer(args[0]).intValue();

                        int w=Integer.parseInt(args[1]);

                        /*int w=Integer.valueOf(args[1]).intValue();*/

                        //StringBuffer sb=new StringBuffer();

                        for(int i=0;i<h;i++)

                        {

                               //sb定義在這里,可以省略下面用“//”注釋的語句。

                               StringBuffer sb=new StringBuffer();

                               for(int j=0;j<w;j++)

                               {

                                      sb.append('*');      

                               }

                               System.out.println(sb.toString());

                               //sb.delete(0,h+1);

                        }

                 }    

          }

          集合類

          集合類用于存儲一組對象,其中的每個對象稱之為元素,經常會用到的有VectorEnumerationArrayListCollectionIteratorSetList等集合類和接口。

               Vector類與Enumeration接口。

                   編程舉例:將鍵盤上輸入的數字序列中的每位數字存儲在Vector對象中,然后在屏幕上打印出每位數字相加的結果,例如,輸入32,打印出5;輸入1234,打印出10。

          import java.util.*;

          public class TestVector

          {

              public static void main(String[] args)

              {

                  int sum=0;

                  Vector v=new Vector();

                  System.out.println("請輸入數字:");

                  while(true)

                  {

                      int b=0;

                      try{b=System.in.read();}catch(Exception ex){ex.printStackTrace();}

                      if(b=='\r'||b=='\n')

                          break;

                      else

                      {

                          int num=b-'0';

                          v.addElement(new Integer(num));

                      }  

                  }

                  Enumeration e=v.elements();

                  while(e.hasMoreElements())

                  {

                      Integer intObj=(Integer)e.nextElement();

                      sum+=intObj.intValue();

                      //sum+=((Integer)e.nextElement()).intValue();

                  }

                  System.out.println(sum);

              }  

          }

               Collection接口與Iterator接口

          編程舉例:用ArrayListIterator改寫上面的例子程序。

          import java.util.*;

          public class TestCollection

          {

          public static void main(String[] args)

          {

                  int sum=0;

                  ArrayList al=new ArrayList();

                  System.out.println("請輸入數字:");

                  while(true)

                  {

                         int b=0;

                         try{b=System.in.read();}catch(Exception e){e.printStackTrace();}

                         if(b=='\r'||b=='\n')

                         {

                                break;

                         }

                         else

                         {

                                int num=b-'0';

                                al.add(new Integer(num));

                         }

                  }

                  Iterator it=al.iterator();

                  while(it.hasNext())

                  {

                         sum+=((Integer)it.next()).intValue();

                  }

                  System.out.println(sum);

          }    

          }

          注意:在何種情況下使用VectorArrayList?

          Vcetor類中的所有方法都是線程同步的,如果有兩個線程并發的訪問同一個Vector對象,這是安全的。即使有一個線程訪問Vector對象時,同步監視器也是的運行的,這樣程序的運行效率就會降低。ArrayList類中的所有方法都不是線程同步的,如果程序中不存在多線程安全問題,使用ArrayList會比使用Vector效率高些;如果程序中存在多線程安全問題,使用ArrayList則需要用戶自己對訪問ArrayList對象的程序代碼進行同步處理,使用Vector則不需要這樣做。

               CollectionSetList的區別如下:

          CollectionSetList的父類,

                   Collection各元素對象之間沒有指定的順序,允許有重復元素和多個null元素對象

                   Set各元素對象之間沒有指定的順序,不允許有重復元素和最多允許有一個null元素對象

                   List各元素對象之間有指定的順序,允許有重復元素和多個null元素對象

          import java.util.*;

          public class TestSort

          {

                 public static void main(String[] args)

                 {

                        ArrayList al=new ArrayList();

                        al.add(new Integer(2));

                        al.add(new Integer(5));

                        al.add(new Integer(1));

                        System.out.println(al.toString());

                        Collections.sort(al);

                        System.out.println(al.toString());

                 }    

          }

           

          Hashtable

          Hashtable不僅可以像Vector一樣動態存儲一系列的對象,而且對存儲的每一個對象(稱為值)都要安排另一個對象(稱為關鍵字)與之相關聯。

          例:

                 創建了一個數字的哈希表

                 Hashtable numbers=new Hashtable();

                 numbers.put(“one”,new Integer(1));

                 numbers.put(“two”,new Integer(2));

                 numbers.put(“three”,new Integer(3));

          如存在相同關鍵字,則修改原來的關鍵字所對應的值。

                 要檢索一個數字

                 Integer n=(Integer)numbers.get(“two”);

                 If(n!=null)

                        {

                               System.out.println(“tow=’+n);

                        }

          用作關鍵字的類必須覆蓋Object.hashCode方法和Object.equals方法。

          編程舉例:使用自定義類作為Hashtable的關鍵字類

          HashTableTest

          import java.util.*;

          public class HashTableTest

          {

                 public static void main(String[] args)

                 {

                        Hashtable numbers=new Hashtable();

                        numbers.put(new MyKey("zhangsan",18),new Integer(1));

                        numbers.put(new MyKey("lisi",15),new Integer(2));

                        numbers.put(new MyKey("wangwu",20),new Integer(3));

                       

                        Enumeration e=numbers.keys();

                        while(e.hasMoreElements())

                        {

                               MyKey key=(MyKey)e.nextElement();

                               System.out.print(key.toString()+"=");

                               System.out.println(numbers.get(key));

                        }

                        System.out.println(numbers.get(new MyKey("zhangsan",18)));        

                 }    

          }

          MyKey

          public class MyKey

          {

                 private String name = null;

                 private int age = 0; 

                 public MyKey(String name,int age)

                 {

                        this.name=name;

                        this.age=age;

                 }

           

                 public boolean equals(Object obj)

                 {

                        if(obj instanceof MyKey)

                        {

                               MyKey key=(MyKey)obj;

                               if(name.equals(key.name)&&age==key.age)

                               {

                                      return true;

                               }

                               else

                               {

                                      return false;

                               }

                        }

                        else

                        {

                               return false;

                        }

                 }

                

                 public int hashCode()

                 {

                        return name.hashCode()+age;

                 }

           

                 public String toString()

                 {

                        return name+","+age;

                 }    

          }

          Properties

               Properties類是Hashtable的子類

               增加了將Hashtable對象中的關鍵字和值保存到文件和從文件中讀取關鍵字和值到Hashtable對象中的方法。

               如果要用Properties.store方法存儲Properties對象中的內容,每個屬性的關鍵字和值都必須是String類型

          編程舉例:使用Prperties把程序的啟動運行記錄在某個文件中,每次運行時打印出它的運行次數。

          import java.util.Properties;

          import java.io.*;

          public class PropertiesFile

          {

           

                 public static void main(String[] args)

                 {

                        // TODO: Add your code here

                        Properties setting=new Properties();

                        try

                        {

                               setting.load(new FileInputStream("count.txt"));

                        }

                        catch(Exception e)

                        {

                               setting.setProperty("count",String.valueOf(0));

                        }

                        int n=Integer.parseInt(setting.getProperty("count"))+1;

                        System.out.println("Times:"+n);

                        setting.setProperty("count",String.valueOf(n));

                        try

                        {

                               setting.store(new FileOutputStream("count.txt"),"Program used:");

                        }

                        catch(Exception e)

                        {

                               e.printStackTrace();

                        }

                       

                 }    

          }

          SystemRuntime

               System

          n         Exit方法

                 public static void exit(int status)

          終止當前正在運行的 Java 虛擬機。參數用作狀態碼;根據慣例,非零的狀態碼表示異常終止,零為正常終止

          該方法調用 Runtime 類中的 exit 方法。該方法永遠不會正常返回。

          調用 System.exit(n) 實際上等效于調用:

           Runtime.getRuntime().exit(n)
          •     CurrentTimeMillis方法
                 public static long currentTimeMillis()

          返回以毫秒為單位的當前時間。注意,當返回值的時間單位是毫秒時,值的粒度取決于基礎操作系統,并且粒度可能更大。例如,許多操作系統以幾十毫秒為單位測量時間。

          返回:

          當前時間與協調世界時 1970 1 1 日午夜之間的時間差(以毫秒為單位測量)。

          •          Java虛擬機的系統屬性
          •        GetPropertiessetProperties方法

          getProperties

                 public static Properties getProperties()

          確定當前的系統屬性。

          setProperties

                 public static void setProperties(Properties props)

          將系統屬性設置為 Properties 參數。

          getProperty

                 public static String getProperty(String key)

          獲得指定鍵指示的系統屬性

          setProperty

                 public static String setProperty(String key,String value)

          設置指定鍵指示的系統屬性。

          參數:

          key - 系統屬性的名稱。

          value - 系統屬性的值。

          返回:

          系統屬性以前的值,如果沒有以前的值,則返回 null

          編程實例:列出Java虛擬機的系統屬性

          import java.util.*;

          public class TestProperties

          {

                 public static void main(String[] args)

                 {

                        long startTime=System.currentTimeMillis();

                        Properties pp=System.getProperties();

                        pp.setProperty("name","jianke");

                        System.setProperties(pp);

                        Enumeration e=pp.propertyNames();

                        while(e.hasMoreElements())

                        {

                               String key=(String)e.nextElement();

                               System.out.println(key+System.getProperty(key));

                        }

                        long endTime=System.currentTimeMillis();

                        System.out.println("此程序啟動運行時間:"+(endTime-startTime)+"ms");

                 }    

          }

               Runtime

          在單獨的進程中執行指定的字符串命令。

          •          public void exit(int status)

          通過啟動虛擬機的關閉序列,終止當前正在運行的 Java 虛擬機。此方法從不正常返回。可以將變量作為一個狀態碼;根據慣例,非零的狀態碼表示非正常終止。

          •         public static Runtime getRuntime()

          返回與當前 Java 應用程序相關的運行時對象。Runtime 類的大多數方法是實例方法,并且必須根據當前的運行時對象對其進行調用。

          編程實例:在Java程序中啟動一個Windows記事本程序運行實例,并在該運行實例中打開這個Java程序的源文件,啟動的記事本程序5秒鐘后被關閉。

           

          public class TestRunTime

          {

                 public static void main(String[] args)

                 {

                        Process p=null;

                        try

                        {

                               p=Runtime.getRuntime().exec("notepad.exe TestRunTime.java");

                               Thread.sleep(5000);

                               p.destroy();

                        }

                        catch(Exception e)

                        {

                               e.printStackTrace();

                        }

                 }    

          }

          Destroy(Process方法)

          public abstract void destroy()

          殺掉子進程。強制終止此 Process 對象表示的子進程。

          與日期和時間有關的類

               最常用幾個類:Date、DateFormat和Calendar

               Calendar類

          Calendar 提供了一個類方法 getInstance,以獲得此類型的一個通用的對象。CalendargetInstance 方法返回一個 Calendar 對象,其日歷字段已由當前日期和時間初始化:

               Calendar rightNow = Calendar.getInstance();
               public abstract void add(int field, int amount)

          根據日歷的規則,為給定的日歷字段添加或減去指定的時間量。例如,要從當前日歷時間減去 5 天,可以通過調用以下方法做到這一點:

          add(Calendar.DAY_OF_MONTH, -5)

          參數:

          field - 日歷字段。

          amount - 為字段添加的日期或時間量

          public int get(int field)

          返回給定日歷字段的值。

               ◆ public void set(int field,int value)

          將給定的日歷字段設置為給定值

          參數:

          field - 給定的日歷字段。

          value - 給定日歷字段所要設置的值。

               GrlendarCalendar子類

          編程實例:計算出距當前日期時間315天后的日期,并用“XXXXXXXXXX小時:XX分:XX秒”的格式輸出。

          import java.util.Calendar;

          public class TestCalendar

          {

                 public static void main(String[] args)

                 {

                        Calendar c=Calendar.getInstance();

          System.out.println(c.get(c.YEAR)+""+

          c.get(c.MONTH) +""+c.get(c.DAY_OF_MONTH)+""+

          c.get(c.HOUR_OF_DAY)+":"+c.get(c.MINUTE)+":"+c.get(c.SECOND));

                        c.add(c.DAY_OF_YEAR,315);

                        System.out.println(c.get(c.YEAR)+""+

          c.get(c.MONTH) +""+c.get(c.DAY_OF_MONTH)+""+                           c.get(c.HOUR_OF_DAY)+":"+c.get(c.MINUTE)+":"+c.get(c.SECOND));

                 }    

          }

               Date

               Java.text.DateFormatgjava.text.SimpleDateFormat子類

          SimpleDateFormat()
                    
          用默認的模式和默認語言環境的日期格式符號構造 SimpleDateFormat

          SimpleDateFormat(String pattern)
                    
          用給定的模式和默認語言環境的日期格式符號構造 SimpleDateFormat

           
           public abstract class DateFormat extends Format

          DateFormat 是日期/時間格式化子類的抽象類,它以與語言無關的方式格式化并分析日期或時間。日期/時間格式化子類(如 SimpleDateFormat)允許進行格式化(也就是日期 -> 文本)、分析(文本-> 日期)和標準化。將日期表示為 Date 對象,或者表示為從 GMT(格林尼治標準時間)1970 年,1 月 1 日 00:00:00 這一刻開始的毫秒數。

          public class SimpleDateFormat extends DateFormat

          SimpleDateFormat 是一個以與語言環境相關的方式來格式化和分析日期的具體類。它允許進行格式化(日期 -> 文本)、分析(文本 -> 日期)和規范化。

          SimpleDateFormat 使得可以選擇任何用戶定義的日期-時間格式的模式。但是,仍然建議通過 DateFormat 中的 getTimeInstancegetDateInstancegetDateTimeInstance 來新的創建日期-時間格式化程序

          編程實例:將“2002-03-15”格式的日期字符串轉換成“20020315日”的格式。

          import java.util.*;

          import java.text.*;

          public class TestCalendar

          {

          public static void main(String[] args)

          {

                  SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");

                  SimpleDateFormat sdf2=new SimpleDateFormat("yyyyMMdd");

                  try

                  {

                         Date d=sdf1.parse("2002-03-15");

                         System.out.println(sdf2.format(d));     

                  }

                  catch(Exception e)

                  {

                         e.printStackTrace();

                  }

                  System.out.println(new Date());

          }    

          }

          TimerTimerTask

          構造方法摘要

          Timer()
                    
          創建一個新計時器。

           

          Timer(boolean isDaemon)
                    
          創建一個新計時器,可以指定其相關的線程作為守護程序運行。

           

          Timer(String name)
                    
          創建一個新計時器,其相關的線程具有指定的名稱。

           

          Timer(String name, boolean isDaemon)
                    
          創建一個新計時器,其相關的線程具有指定的名稱,并且可以指定作為守護程序運行。

           

           

               Schedule方法主要有如下幾種重載形式:

          方法摘要

          void

          schedule(TimerTask task, Date time)
                    
          安排在指定的時間執行指定的任務。

          task - 所要安排的任務。

          time - 執行任務的時間。

           void

          schedule(TimerTask task, Date firstTime, long period)
                    
          安排指定的任務在指定的時間開始進行重復的固定延遲執行

          task - 所要安排的任務。

          firstTime - 首次執行任務的時間。

          period - 執行各后續任務之間的時間間隔,單位是毫秒。

           void

          schedule(TimerTask task, long delay)

                    安排在指定延遲后執行指定的任務。

          task - 所要安排的任務。

          delay - 執行任務前的延遲時間,單位是毫秒。

           void

          schedule(TimerTask task, long delay, long period)
                    
          安排指定的任務從指定的延遲后開始進行重復的固定延遲執行

          task - 所要安排的任務。

          delay - 執行任務前的延遲時間,單位是毫秒。

          period - 執行各后續任務之間的時間間隔,單位是毫秒。

               TimerTask類實例了Runnable接口,要執行的任務由它里面實現的run方法來完成。

          編程實例:程序啟動運行30秒啟動Windows自帶的計算器程序。

          import java.util.*;

          public class TestTimer

          {

          public static void main(String[] args)

          {

                  Timer tm=new Timer();

                  tm.schedule(new MyTimerTask(tm),30000);

          }    

          }

           

          class MyTimerTask extends TimerTask

          {

          private Timer tm=null;

          public MyTimerTask(Timer tm)

          {

                  this.tm=tm;    

          }

          public void run()

          {

                  try

                  {

                         Runtime.getRuntime().exec("calc.exe");

                  }

                  catch(Exception e)

                  {

                         e.printStackTrace();

                  }

                  //結束任務的線程代碼

                  tm.cancel();

          }

          }

          MathRandom

               Math類包含了所有用于幾何和三角運算的方法

               Random類是一個偽隨機數產生器

          int

          nextInt()
                    
          返回下一個偽隨機數,它是此隨機數生成器的序列中均勻分布的 int 值。

           int

          nextInt(int n)
                    
          返回一個偽隨機數,它是從此隨機數生成器的序列中取出的、在 0(包括)和指定值(不包括)之間均勻分布的 int值。

          例:      

          public static void main(String[] args)

                 {

                        Random rd=new Random();

                        System.out.println(rd.nextInt(100));    

                 }

           

          posted on 2007-07-02 12:04 大頭劍客 閱讀(1004) 評論(0)  編輯  收藏 所屬分類: 學習筆記

          <2025年7月>
          293012345
          6789101112
          13141516171819
          20212223242526
          272829303112
          3456789

          導航

          統計

          公告

          寫字樓里寫字間,寫字間里程序員;
          程序人員寫程序,又拿程序換酒錢;
          酒醒只在網上坐,酒醉還來網下眠;
          酒醉酒醒日復日,網上網下年復年;
          但愿老死電腦間,不愿鞠躬老板前;
          奔馳寶馬貴者趣,公交自行程序員;
          別人笑我忒瘋癲,我笑自己命太賤;
          不見滿街漂亮妹,哪個歸得程序員.
          不管前面是地雷陣還是萬丈深淵,
          我都將勇往直前,義無反顧,
          鞠躬盡瘁,死而后已。
          —— 朱镕基總理

          常用鏈接

          留言簿(1)

          隨筆檔案

          文章分類

          文章檔案

          學習園地

          最新隨筆

          搜索

          積分與排名

          最新評論

          主站蜘蛛池模板: 新乐市| 孟津县| 安远县| 永泰县| 鄯善县| 顺平县| 莱州市| 河北区| 泸水县| 延安市| 名山县| 马尔康县| 泾阳县| 蓝田县| 古蔺县| 广德县| 青田县| 安平县| 米脂县| 汝城县| 蓝山县| 苏州市| 姚安县| 中牟县| 城市| 年辖:市辖区| 库尔勒市| 东海县| 永胜县| 孝义市| 瑞安市| 资源县| 称多县| 南和县| 邹城市| 广昌县| 丰顺县| 县级市| 乐昌市| 泌阳县| 上高县|