第六章 Java API
第六講 Java API
● 理解API的概念
● java輔助工具的使用
● String類和StringBuffer類
● 基本數(shù)據(jù)類型的對(duì)象包裝類
● 集合類
● Hashtable與Properties類
● System類與Runtime類
● Date、Calendar與DateFormat類
● Timer與TimerTask類
● Math與Random類
● 學(xué)習(xí)API的方法
理解API的概念
● API的概念
(Application Programming Interface)
● Window API
就是Windows操作系統(tǒng)提供的各種函數(shù),例如,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
● 工作區(qū)(jcw)與工程(jcp)
● 使用類向?qū)?chuàng)建新類
● 使用動(dòng)態(tài)隨筆功能和自動(dòng)輸入功能
● 指定Jcreator所有使用的JDK
● 設(shè)置第三方提供的Jar包
● 指定啟動(dòng)運(yùn)行類及參數(shù)
● 設(shè)置多個(gè)運(yùn)行配置環(huán)境
String類和StringBuffer類
● 位于java.lang包中。
● String類對(duì)象中的內(nèi)容一旦被初始化就不能再改變。
● StringBuffer類用于封閉內(nèi)容可以改變的字符串。
用toString方法轉(zhuǎn)換成String類型
String x=”a”+4+”c”,編譯時(shí)等效于:
String x=new StringBuffer().append(“a”).append(4).append(“c”).toString();
● 字符串常量(如”hello”)實(shí)際上是一種特殊的匿名String對(duì)象。比較下面兩種情況的差異:
● String s1=”hello”; String s2=”hello”;
● String s1=new String(“hello”); String s2=new String(“hello”);
編程實(shí)例:逐行讀取鍵盤輸入,直到輸入內(nèi)容為”bye”時(shí),結(jié)束程序。
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("請(qǐng)輸入內(nèi)容:");
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類的常用成員方法
● 構(gòu)造方法:
● String
(byte[]
bytes, int
offset, int
length)
構(gòu)造一個(gè)新的 String,方法是使用指定的字符集解碼字節(jié)的指定子數(shù)組。
● charAt
(int
index)
返回指定索引處的 char
值
● compareTo
(String
anotherString)
按字典順序比較兩個(gè)字符串。
● indexOf
(int
ch)
返回指定字符在此字符串中第一次出現(xiàn)處的索引。如果不存在這樣的值,則返回 -1。
例:strName.indexOf(‘a’);
● indexOf
(int
ch, int
fromIndex)
從指定的索引開(kāi)始搜索,返回在此字符串中第一次出現(xiàn)指定字符處的索引。
● indexOf
(String
str)
返回第一次出現(xiàn)的指定子字符串在此字符串中的索引。
● indexOf
(String
str, int
fromIndex)
從指定的索引處開(kāi)始,返回第一次出現(xiàn)的指定子字符串在此字符串中的索引。
● length
()
返回此字符串的長(zhǎng)度。
● substring
(int
beginIndex)
返回一個(gè)新的字符串,它是此字符串的一個(gè)子字符串。
● substring
(int
beginIndex, int
endIndex)
返回一個(gè)新字符串,它是此字符串的一個(gè)子字符串。
● toLowerCase
()
使用默認(rèn)語(yǔ)言環(huán)境的規(guī)則將此 String
中的所有字符都轉(zhuǎn)換為小寫。
● toUpperCase
()
使用默認(rèn)語(yǔ)言環(huán)境的規(guī)則將此 String
中的所有字符都轉(zhuǎn)換為大寫。
● valueOf
(int
i)
返回 int
參數(shù)的字符串表示形式。
● ………………………………………………………..
|
●
基本數(shù)據(jù)類型的對(duì)象包裝類
● 基本數(shù)據(jù)類型包裝類的作用
基本數(shù)據(jù)類型 |
包裝類 |
boolean |
Boolean |
byte |
Byte |
char |
Character |
short |
Short |
Int |
Integer |
Long |
Long |
float |
Float |
double |
Double |
編程實(shí)例:將字符串轉(zhuǎn)換成整數(shù)的編程舉例
在屏幕上打印出一個(gè)星號(hào)(*)組成的矩形,矩形的寬度和高度通過(guò)啟動(dòng)程序時(shí)傳遞給main方法的參數(shù)指定,并比較下面兩段代碼的運(yùn)行效率:
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(*);
} }
以下黑粗體部分是“字符串轉(zhuǎn)換成整數(shù)”的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定義在這里,可以省略下面用“//”注釋的語(yǔ)句。
StringBuffer sb=new StringBuffer();
for(int j=0;j<w;j++)
{
sb.append('*');
}
System.out.println(sb.toString());
//sb.delete(0,h+1);
}
}
}
集合類
集合類用于存儲(chǔ)一組對(duì)象,其中的每個(gè)對(duì)象稱之為元素,經(jīng)常會(huì)用到的有Vector、Enumeration、ArrayList、Collection、Iterator、Set、List等集合類和接口。
● Vector類與Enumeration接口。
編程舉例:將鍵盤上輸入的數(shù)字序列中的每位數(shù)字存儲(chǔ)在Vector對(duì)象中,然后在屏幕上打印出每位數(shù)字相加的結(jié)果,例如,輸入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("請(qǐng)輸入數(shù)字:");
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接口
編程舉例:用ArrayList和Iterator改寫上面的例子程序。
import java.util.*;
public class TestCollection
{
public static void main(String[] args)
{
int sum=0;
ArrayList al=new ArrayList();
System.out.println("請(qǐng)輸入數(shù)字:");
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);
}
}
注意:在何種情況下使用Vector和ArrayList?
Vcetor類中的所有方法都是線程同步的,如果有兩個(gè)線程并發(fā)的訪問(wèn)同一個(gè)Vector對(duì)象,這是安全的。即使有一個(gè)線程訪問(wèn)Vector對(duì)象時(shí),同步監(jiān)視器也是的運(yùn)行的,這樣程序的運(yùn)行效率就會(huì)降低。ArrayList類中的所有方法都不是線程同步的,如果程序中不存在多線程安全問(wèn)題,使用ArrayList會(huì)比使用Vector效率高些;如果程序中存在多線程安全問(wèn)題,使用ArrayList則需要用戶自己對(duì)訪問(wèn)ArrayList對(duì)象的程序代碼進(jìn)行同步處理,使用Vector則不需要這樣做。
● Collection、Set、List的區(qū)別如下:
Collection是Set和List的父類,
Collection各元素對(duì)象之間沒(méi)有指定的順序,允許有重復(fù)元素和多個(gè)null元素對(duì)象
Set各元素對(duì)象之間沒(méi)有指定的順序,不允許有重復(fù)元素和最多允許有一個(gè)null元素對(duì)象
List各元素對(duì)象之間有指定的順序,允許有重復(fù)元素和多個(gè)null元素對(duì)象
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一樣動(dòng)態(tài)存儲(chǔ)一系列的對(duì)象,而且對(duì)存儲(chǔ)的每一個(gè)對(duì)象(稱為值)都要安排另一個(gè)對(duì)象(稱為關(guān)鍵字)與之相關(guān)聯(lián)。
例:
創(chuàng)建了一個(gè)數(shù)字的哈希表
Hashtable numbers=new Hashtable();
numbers.put(“one”,new Integer(1));
numbers.put(“two”,new Integer(2));
numbers.put(“three”,new Integer(3));
注:如存在相同關(guān)鍵字,則修改原來(lái)的關(guān)鍵字所對(duì)應(yīng)的值。
要檢索一個(gè)數(shù)字
Integer n=(Integer)numbers.get(“two”);
If(n!=null)
{
System.out.println(“tow=’+n);
}
用作關(guān)鍵字的類必須覆蓋Object.hashCode方法和Object.equals方法。
編程舉例:使用自定義類作為Hashtable的關(guān)鍵字類
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對(duì)象中的關(guān)鍵字和值保存到文件和從文件中讀取關(guān)鍵字和值到Hashtable對(duì)象中的方法。
● 如果要用Properties.store方法存儲(chǔ)Properties對(duì)象中的內(nèi)容,每個(gè)屬性的關(guān)鍵字和值都必須是String類型
編程舉例:使用Prperties把程序的啟動(dòng)運(yùn)行記錄在某個(gè)文件中,每次運(yùn)行時(shí)打印出它的運(yùn)行次數(shù)。
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();
}
}
}
System與Runtime類
● System類
n Exit方法
public static void exit(int status)
終止當(dāng)前正在運(yùn)行的 Java 虛擬機(jī)。參數(shù)用作狀態(tài)碼;根據(jù)慣例,非零的狀態(tài)碼表示異常終止,零為正常終止。
該方法調(diào)用 Runtime
類中的 exit
方法。該方法永遠(yuǎn)不會(huì)正常返回。
調(diào)用 System.exit(n)
實(shí)際上等效于調(diào)用:
Runtime.getRuntime().exit(n)
- CurrentTimeMillis方法
public static long currentTimeMillis()
返回以毫秒為單位的當(dāng)前時(shí)間。注意,當(dāng)返回值的時(shí)間單位是毫秒時(shí),值的粒度取決于基礎(chǔ)操作系統(tǒng),并且粒度可能更大。例如,許多操作系統(tǒng)以幾十毫秒為單位測(cè)量時(shí)間。
返回:
當(dāng)前時(shí)間與協(xié)調(diào)世界時(shí) 1970 年 1 月 1 日午夜之間的時(shí)間差(以毫秒為單位測(cè)量)。
- Java虛擬機(jī)的系統(tǒng)屬性
- GetProperties和setProperties方法
getProperties
public static Properties getProperties()
確定當(dāng)前的系統(tǒng)屬性。
setProperties
public static void setProperties(Properties props)
將系統(tǒng)屬性設(shè)置為 Properties
參數(shù)。
getProperty
public static String getProperty(String key)
獲得指定鍵指示的系統(tǒng)屬性
setProperty
public static String setProperty(String key,String value)
設(shè)置指定鍵指示的系統(tǒng)屬性。
參數(shù):
key
- 系統(tǒng)屬性的名稱。
value
- 系統(tǒng)屬性的值。
返回:
系統(tǒng)屬性以前的值,如果沒(méi)有以前的值,則返回 null
。
編程實(shí)例:列出Java虛擬機(jī)的系統(tǒng)屬性
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("此程序啟動(dòng)運(yùn)行時(shí)間:"+(endTime-startTime)+"ms");
}
}
● Runtime類
- public Process exec(String command) throws IOException
在單獨(dú)的進(jìn)程中執(zhí)行指定的字符串命令。
- public void exit(int status)
通過(guò)啟動(dòng)虛擬機(jī)的關(guān)閉序列,終止當(dāng)前正在運(yùn)行的 Java 虛擬機(jī)。此方法從不正常返回??梢詫⒆兞孔鳛橐粋€(gè)狀態(tài)碼;根據(jù)慣例,非零的狀態(tài)碼表示非正常終止。
- public static Runtime getRuntime()
返回與當(dāng)前 Java 應(yīng)用程序相關(guān)的運(yùn)行時(shí)對(duì)象。Runtime
類的大多數(shù)方法是實(shí)例方法,并且必須根據(jù)當(dāng)前的運(yùn)行時(shí)對(duì)象對(duì)其進(jìn)行調(diào)用。
編程實(shí)例:在Java程序中啟動(dòng)一個(gè)Windows記事本程序運(yùn)行實(shí)例,并在該運(yùn)行實(shí)例中打開(kāi)這個(gè)Java程序的源文件,啟動(dòng)的記事本程序5秒鐘后被關(guān)閉。
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()
殺掉子進(jìn)程。強(qiáng)制終止此 Process
對(duì)象表示的子進(jìn)程。
與日期和時(shí)間有關(guān)的類
● 最常用幾個(gè)類:Date、DateFormat和Calendar
● Calendar類
Calendar
提供了一個(gè)類方法 getInstance
,以獲得此類型的一個(gè)通用的對(duì)象。Calendar
的 getInstance
方法返回一個(gè) Calendar
對(duì)象,其日歷字段已由當(dāng)前日期和時(shí)間初始化:
Calendar rightNow = Calendar.getInstance();
◆ public abstract void add(int field, int amount)
根據(jù)日歷的規(guī)則,為給定的日歷字段添加或減去指定的時(shí)間量。例如,要從當(dāng)前日歷時(shí)間減去 5 天,可以通過(guò)調(diào)用以下方法做到這一點(diǎn):
add(Calendar.DAY_OF_MONTH, -5)
。
參數(shù):
field
- 日歷字段。
amount
- 為字段添加的日期或時(shí)間量
◆ public int get(int field)
返回給定日歷字段的值。
◆ public void set(int field,int value)
將給定的日歷字段設(shè)置為給定值
參數(shù):
field
- 給定的日歷字段。
value
- 給定日歷字段所要設(shè)置的值。
◆ GrlendarCalendar子類
編程實(shí)例:計(jì)算出距當(dāng)前日期時(shí)間315天后的日期,并用“XXXX年XX月XX日XX小時(shí):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.DateFormatg與java.text.SimpleDateFormat子類
|
|
public abstract class DateFormat extends Format
DateFormat 是日期/時(shí)間格式化子類的抽象類,它以與語(yǔ)言無(wú)關(guān)的方式格式化并分析日期或時(shí)間。日期/時(shí)間格式化子類(如 SimpleDateFormat)允許進(jìn)行格式化(也就是日期 -> 文本)、分析(文本-> 日期)和標(biāo)準(zhǔn)化。將日期表示為 Date
對(duì)象,或者表示為從 GMT(格林尼治標(biāo)準(zhǔn)時(shí)間)1970 年,1 月 1 日 00:00:00 這一刻開(kāi)始的毫秒數(shù)。
public class SimpleDateFormat extends DateFormat
SimpleDateFormat
是一個(gè)以與語(yǔ)言環(huán)境相關(guān)的方式來(lái)格式化和分析日期的具體類。它允許進(jìn)行格式化(日期 -> 文本)、分析(文本 -> 日期)和規(guī)范化。
SimpleDateFormat
使得可以選擇任何用戶定義的日期-時(shí)間格式的模式。但是,仍然建議通過(guò) DateFormat
中的 getTimeInstance
、getDateInstance
或 getDateTimeInstance
來(lái)新的創(chuàng)建日期-時(shí)間格式化程序
編程實(shí)例:將“2002-03-15”格式的日期字符串轉(zhuǎn)換成“2002年03月15日”的格式。
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("yyyy年MM月dd日");
try
{
Date d=sdf1.parse("2002-03-15");
System.out.println(sdf2.format(d));
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println(new Date());
}
}
Timer與TimerTask類
構(gòu)造方法摘要 |
|
|
|
|
|
|
|
|
|
● Schedule方法主要有如下幾種重載形式:
方法摘要
|
|
|
|
|
安排在指定延遲后執(zhí)行指定的任務(wù)。
|
|
|
● TimerTask類實(shí)例了Runnable接口,要執(zhí)行的任務(wù)由它里面實(shí)現(xiàn)的run方法來(lái)完成。
編程實(shí)例:程序啟動(dòng)運(yùn)行30秒啟動(dòng)Windows自帶的計(jì)算器程序。
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();
}
//結(jié)束任務(wù)的線程代碼
tm.cancel();
}
}
Math與Random類
● Math類包含了所有用于幾何和三角運(yùn)算的方法
● Random類是一個(gè)偽隨機(jī)數(shù)產(chǎn)生器
|
|
|
|
例:
public static void main(String[] args)
{
Random rd=new Random();
System.out.println(rd.nextInt(100));
}
posted on 2007-07-02 12:04 大頭劍客 閱讀(1005) 評(píng)論(0) 編輯 收藏 所屬分類: 學(xué)習(xí)筆記