Java經(jīng)典實(shí)例(第二版)_第1頁(yè)
Java經(jīng)典實(shí)例(第二版)_第2頁(yè)
Java經(jīng)典實(shí)例(第二版)_第3頁(yè)
Java經(jīng)典實(shí)例(第二版)_第4頁(yè)
Java經(jīng)典實(shí)例(第二版)_第5頁(yè)
已閱讀5頁(yè),還剩42頁(yè)未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

Java經(jīng)典實(shí)例(第二版)

1.獲取環(huán)境變量

Java代碼

1.System,getenv(〃PATH〃);

2.System,getenv(,zJAVA_HOME,/);

2.獲取系統(tǒng)屬性

Java代碼

1.System.getProperty("'pencilcolor");//得到屬性值

2.java-Dpencilcolor=green

3.System.getProperty(z/java.specification,version");//得至

Java版本號(hào)

4.Propertiesp=System.getProperties();//得到所有屬性

5.p.list(System,out);

3.StringTokenizer

Java代碼

1.//能夠同時(shí)識(shí)別,和I

2.StringTokenizerst=newStringTokenizerC'Hello,World|of|

Javaz,,〃,|z/);

3.while(st.hasMoreElements0){

4.st.nextToken();

5.)

6.

7.//把分隔符視為token

8.StringTokenizerst=newStringTokenizer(,zHello,World|of|

Java”,〃,|〃,true);

4.StringBuffer(同步)和StringBuilder(非同步)

Java代碼

1.StringBuildersb=newStringBuilder();

2.sb.append(〃Hello〃);

3.sb.append(z,Worldz,);

4.sb.toStringO;

5.newStringBuffer(a).reverse0;//反轉(zhuǎn)字符串

5.數(shù)字

Java代碼

1.//數(shù)字與對(duì)象之間互相轉(zhuǎn)換-Integer轉(zhuǎn)int

2.Integer.intValue();

3.

4.//浮點(diǎn)數(shù)的舍入

5.Math,round()

6.

7.//數(shù)字格式化

8.NumberFormat

9.

10.//整數(shù)->二進(jìn)制字符串

11.toBinaryString()或valueOf()

12.

13.//整數(shù)->八進(jìn)制字符串

14.toOctalStringO

15.

16.//整數(shù)->十六進(jìn)制字符串

17.toHexStringO

18.

19.//數(shù)字格式化為羅馬數(shù)字

20.RomanNumberFormat()

21.

22.//隨機(jī)數(shù)

23.Randomr=newRandom();

24.r.nextDouble();

25.r.nextlnt();

6.日期和時(shí)間

Java代碼

1.//查看當(dāng)前日期

2.Datetoday=newDateO;

3.Calendar,getlnstance().getTime();

4.

5.//格式化默認(rèn)區(qū)域日期輸出

6.DateFormatdf=DateFormat.getlnstance();

7.df.format(today);

8.

9.//格式化制定區(qū)域日期輸出

10.DateFormatdf_cn=DateFormat.getDatelnstance(DateFormat.FUL

L,Locale.CHINA);

11.Stringnow=df_cn.format(today);

12.

13.//按要求格式打印日期

14.SimpleDateFormatsdf=newSimpleDateFormat(,zyyyy-MM-ddhh

:mm:ss〃);

15.sdf.format(today);

16.

17.//設(shè)置具體日期

18.GregorianCalendardl=newGregorianCalendar(2009,05,06

);//6月6日

19.GregorianCalendard2=newGregorianCalendar0;//今

20.Calendard3=Calendar,getlnstance();//今天

21.dl.getTime();//Calendar或GregorianCalendar轉(zhuǎn)成Date格

22.d3.set(Calendar.YEAR,1999);

23.d3.set(Calendar.MONTH,Calendar.APRIL);

24.d3.set(Calendar.DAY_0F_M0NTH,12);

25.

26.//字符串轉(zhuǎn)日期

27.SimpleDateFormatsdf=newSimpleDateFormat(,zyyyy-MM-ddhh

:mm:ss〃);

28.Datenow=sdf.parse(String);

29.

30.//日期加減

31.Datenow=newDate();

32.longt=now.getTime();

33.t+=700*24*60*60*1000;

34.Datethen=newDate(t);

35.

36.Calendarnow=Calendar,getlnstance();

37.now.add(Calendar.YEAR,-2);

38.

39.//計(jì)算日期間隔(轉(zhuǎn)換成long來計(jì)算)

40.today.getTimeO-old.getTime();

41.

42.//比較日期

43.Date類型,就使用equals。,before(),after。來計(jì)算

44.long類型,就使用==,<,>來計(jì)算

45.

46.//第幾日

47.使用Calendar的get()方法

48.Calendarc=Calendar.getlnstanceO;

49.c.get(Calendar.YEAR);

50.

51.//記錄耗時(shí)

52.longstart=System.currentTimeMillis();

53.longend=System,current?imeMi11is();

54.longelapsed=end-start;

55.System.nanoTime();〃毫秒

56.

57.//長(zhǎng)整形轉(zhuǎn)換成秒

58.Double.toString(t/1000D);

7.結(jié)構(gòu)化數(shù)據(jù)

Java代碼

1.//數(shù)組拷貝

2.System.arrayCopy(oldArray,0,newArray,0,oldArray.length)

3.

4.//ArrayList

5.add(Objecto)//在末尾添加給定元素

6.add(inti,Objecto)//在指定位置插入給定元素

7.clear()//從集合中刪除全部元素

8.Contains(Objecto)//如果Vector包含給定元素,返回真值

9.get(inti)//返回指定位置的對(duì)象句柄

10.indexOf(Objecto)//如果找到給定對(duì)象,則返回其索引值;否則,

返回T

11.remove(Objecto)//根據(jù)引用刪除對(duì)象

12.remove(inti)//根據(jù)位置刪除對(duì)象

13.toArrayO//返回包含集合對(duì)象的數(shù)組

14.

15.//Iterator

16.Listlist=newArrayList();

17.Iteratorit=list,iterator();

18.while(it.hasNext())

19.Objecto=it.next();

20.

21.//鏈表

22.LinkedListlist=newLinkedList0;

23.Listiteratorit=list,listiterator();

24.while(it.hasNext())

25.Objecto=it.next();

26.

27.//HashMap

28.HashMap<String,String>hm=newHashMap<String,String>(

);

29.hm.get(key);//通過key得到value

30.hm.put(〃Nol〃,〃Hexinyu〃);

31.hm.put(〃No2〃,〃Sean〃);

32.//方法1:獲取全部鍵值

33.Iterator<String>it=hm.values().iterator();

34.while(it.hasNext()){

35.StringmyKey=it.next();

36.StringmyValue=hm.get(myKey);

37.)

38.//方法2:獲取全部鍵值

39.for(Stringkey:hm.keySet()){

40.StringmyKey=key;

41.StringmyValue=hm.get(myKey);

42.}

43.

44.//Preferences-與系統(tǒng)相關(guān)的用戶設(shè)置,類似名-值對(duì)

45.Preferencesprefs=Preferences.userNodeForPackage(ArrayDemo

,class);

46.Stringtext=prefs,getC/textFontName,/,/,lucida-bright,/);

47.Stringdisplay=prefs,get(,,displayFontName/,,“l(fā)ucida-balck

letter");

48.System,out.println(text);

49.System,out.printin(display);

50.//用戶設(shè)置了新值,存儲(chǔ)回去

51.prefs,put("textFontName","new-bright");

52.prefs,put(/zdisplayFontName,z,/znew-balckletter/z);

53.

54.//Properties-類似名-值對(duì),key和value之間,可以用〃二〃,〃:〃

或空格分隔,用〃#〃和〃!〃注釋

55.InputStreamin=MediationServer.class.getClassLoader0.getR

esourceAsStream(,,msconfig.properties");

56.Propertiesprop=newProperties0;

57.prop,load(in);

58.in.close();

59.prop.setProperty(key,value);

60.prop.getProperty(key);

61.

62.//排序

63.1.數(shù)組:Arrays,sort(strings);

64.2.List:Collections,sort(list);

65.3.自定義類:classSubCompimplementsComparator

66.然后使用Arrays,sort(strings,newSubComp())

67.

68.//兩個(gè)接口

69.1.java.lang.Comparable:提供對(duì)象的自然排序,內(nèi)置于類中

70.intcompareTo(Objecto);

71.booleanequals(Objecto2);

72.2.java.util.Comparator:提供特定的比較方法

73.intcompare(Objectol,Objecto2)

74.

75.//避免重復(fù)排序,可以使用TreeMap

76.TreeMapsorted=newTreeMap(unsortedHashMap);

77.

78.//排除重復(fù)元素

79.Hashseths-newHashSet();

80.

81.//搜索對(duì)象

82.binarySearch0:快速查詢-Arrays,Collections

83.contains():線型搜

索-ArrayList,HashSet,Hashtable,linkedList,Propertie

s,Vector

84.containsKeyO:檢查集合對(duì)象是否包含給

定-HashMap,Hashtable,Properties,TreeMap

85.containsValueO:主鍵(或給定

值)-HashMap,Hashtable,Properties,TreeMap

86.indexOf():若找到給定對(duì)象,返回其位

置-ArrayList,linkedList,List,Stack,Vector

87.search():線型搜素-Stack

88.

89.//集合轉(zhuǎn)數(shù)組

90.toArray();

91.

92.//集合總結(jié)

93.Collection:Set-HashSet,TreeSet

94.Collection:List-ArrayList,Vector,LinkedList

95.Map:HashMap,HashTable,TreeMap

8.泛型與foreach

Java代碼

1.//泛型

2.List<String>myList=newArrayList<String>();

3.

4.//foreach

5.for(Strings:myList){

6.System.out.println(s);

7.)

9.面向?qū)ο?/p>

Java代碼

1.//toString。格式化

2.publicclassToStringWith{

3.intx,y;

4.publicToStringWith(intanX,intaY){

5.x=anX;

6.y=aY;

7.)

8.publicStringtoString(){

9.return〃ToStringWith[〃+x+〃,〃+y+

〃]“;

10.)

11.publicstaticvoidmain(String[]args){

12.System,out.println(newToStringWith(43,78));

13.)

14.)

15.

16.//覆蓋equals方法

17.publicbooleanequals(Objecto){

18.if(o==this)//優(yōu)化

19.returntrue;

20.if(!(oinstanceofEqualsDemo))//可投射到這個(gè)

21.returnfalse;

22.EqualsDemoother=(EqualsDemo)o;//類型轉(zhuǎn)

23.if(inti!=other,inti)//按字段比較

24.returnfalse;

25.if(!objl.equals(other,objl))

26.returnfalse;

27.returntrue;

28.)

29.

30.//覆蓋hashcode方法

31.privatevolatileinthashCode=0;〃延遲初始化

32.publicinthashCode(){

33.if(hashCode==0){

34.intresult=17;

35.result=37*result+areaCode;

36.)

37.returnhashCode;

38.)

39.

40.//Clone方法

41.要克隆對(duì)象,必須先做兩步:1.覆蓋對(duì)象的clone。方法;2.實(shí)

現(xiàn)空的Cloneable接口

42.publicclassClonelimplementsCloneable{

43.publicObjectclone(){

44.returnsuper,clone();

45.)

46.}

47.

48.//Finalize方法

49.Objectf=newObject(){

50.publicvoidfinalize(){

51.System,out.printin("Runningfinalize()z/);

52.)

53.}:

54.Runtime.getRuntime().addShutdownHook(newThread(){

55.publicvoidrun(){

56.System,out.printin(zzRunningShutdownHook〃);

57.)

58.});

59.在調(diào)用System,exit(0);的時(shí)候,這兩個(gè)方法將被執(zhí)行

60.

61.//Singleton模式

62.//實(shí)現(xiàn)1

63.publicclassMySingleton(){

64.publicstaticfinalMySingletonINSTANCE=newM

ySingletonO;

65.privateMySingleton0{)

66.)

67.//實(shí)現(xiàn)2

68.publicclassMySingleton(){

69.publicstaticMySingletoninstance=newMySingle

ton();

70.privateMySingleton0{}

71.publicstaticMySingletongetlnstance(){

72.returninstance;

73.)

74.}

75.

76.//自定義異常

77.Exception:編譯時(shí)檢查

78.RuntimeException:運(yùn)行時(shí)檢查

79.publicclassMyExceptionextendsRuntimeException{

80.publicMyExceptionO{

81.super();

82.)

83.publicMyException(Stringmsg){

84.super(msg);

85.}

86.)

10.輸入和輸出

Java代碼

1.//Stream,Reader,Writer

2.Stream:處理字節(jié)流

3.Reader/Writer:處理字符,通用Unicode

4.

5.//從標(biāo)準(zhǔn)輸入設(shè)備讀數(shù)據(jù)

6.1.用System,in的BufferedInputStream()讀取字節(jié)

7.intb=System,in.read();

8.System,out.println(,zReaddata:〃+(char)b);

//強(qiáng)制轉(zhuǎn)換為字符

9.2.BufferedReader讀取文本

10.如果從Stream轉(zhuǎn)成Reader,使用InputStreamReader類

11.BufferedReaderis=newBufferedReader(new

12.InputStreamReader(System,in));

13.StringinputLine;

14.while((inputLine=is.readLine())!=null){

15.System.out.printIn(inputLine);

16.intval=Integer,parselnt(inputLine);

//如果inputLine為整數(shù)

17.)

18.is.close();

19.

20.//向標(biāo)準(zhǔn)輸出設(shè)備寫數(shù)據(jù)

21.1.用System,out的printlnO打印數(shù)據(jù)

22.2.用PrintWriter打印

23.PrintWriterpw=newPrintWriter(System,out);

24.pw.printin("Theansweris〃+myAnswer+〃

atthistime.z/);

25.

26.//Formatter類

27.格式化打印內(nèi)容

28.Formatterfmtr=newFormatter();

29.fmtr.format(z,%l$04d-theyearof%2$f〃,1951,Math.PI);

30.或者System,out.printf();或者

System,out.format();

31.

32.//原始掃描

33.voiddoFile(Readeris){

34.intc;

35.while((c=is.read())!=-1){

36.System.out.printin((char)c);

37.}

38.)

39.

40.//Scanner掃描

41.Scanner可以讀取File,InputStream,String,Readable

42.try{

43.Scannerscan=newScanner(newFile(〃a.txt〃));

44.while(scan.hasNext0){

45.Strings=scan,next();

46.)

47.}catch(FileNotFoundExceptione){

48.e.printStackTrace();

49.}

50.)

51.

52.//讀取文件

53.BufferedReaderis=newBufferedReader(newFileReader(z,myF

ile.txt〃));

54.BufferedOutputStreambos=newBufferedOutputStream(newFi

leOutputStream(z,bytes.bat〃));

55.is.close();

56.bos.close();

57.

58.//復(fù)制文件

59.BufferedlutputStreamis=newBufferedlutputStream(newFil

eIutputStream(z,oldFile.txt"));

60.BufferedOutputStreamos=newBufferedOutputStream(newFil

eOutputStream(^newFile.txt〃));

61.intb;

62.while((b=is.read0)!=T){

63.os.write(b);

64.)

65.is.close();

66.os.close();

67.

68.//文件讀入字符串

69.StringBuffersb=newStringBuffer();

70.char[]b=newchar[8192];

71.intn;

72.//讀一個(gè)塊,如果有字符,加入緩沖區(qū)

73.while((n=is.read(b))>0){

74.sb.append(b,0,n);

75.}

76.returnsb.toStringO;

77.

78.//重定向標(biāo)準(zhǔn)流

79.Stringlogfile="error.log”;

80.System.setErr(newPrintstream(newFileOutputStream(logfile)))

81.

82.//讀寫不同字符集文本

83.BufferedReaderChinese=newBufferedReader(newInputStrea

mReader(newFileInputStream(z,chinese.txtzz),〃IS08859_l〃));

84.PrintWriterstandard=newPrintWriter(newOutputStreamWri

ter(newFileOutputStream(z,standard.txt〃),〃UTF-8〃));

85.

86.//讀取二進(jìn)制數(shù)據(jù)

87.DataOutputStreamos=newDataOutputStream(newFileOutputS

treamC^a.txt"));

88.os.writelnt(i);

89.os.writeDouble(d);

90.os.close();

91.

92.//從指定位置讀數(shù)據(jù)

93.RandomAccessFileraf=newRandomAccessFile(fileName,〃r〃)

;//r表示已只讀打開

94.raf.seek(15);//從15開始讀

95.raf.readlnt();

96.raf.radLineO;

97.

98.//串行化對(duì)象

99.對(duì)象串行化,必須實(shí)現(xiàn)Serializable接口

100.//保存數(shù)據(jù)到磁盤

101.ObjectOutputStreamos=newObjectOutputStream(newBu

fferedOutputStream(newFileOutputStream(FILENAME)));

102.os.writeObject(serialObject);

103.os.close();

104.//讀出數(shù)據(jù)

105.ObjectInputStreamis=newObjectInputStream(newFile

InputStream(FILENAME));

106.is.readObject();

107.is.close();

108.

109.//讀寫Jar或Zip文檔

110.ZipFilezippy=newZipFile(〃a.jar〃);

111.Enumerationall=zippy,entries();//枚舉值列出所

有文件清單

112.while(all.hasMoreElements()){

113.ZipEntryentry=(ZipEntry)all.nextElement();

114.if(entry.isFileO)

115.printIn(''Directory:〃+entry.getName()

);

116.

117.//讀寫文件

118.FileOutputStreamos=newFileOutputStream(ent

ry.getName());

119.InputStreamis=zippy,getInputStream(entry);

120.intn0;

121.byte[]b=newbyte[8092];

122.while((n=is.read(b))>0)

123.os.write(b,0,n);

124.is.close();

125.os.close();

126.}

127.)

128.

129.//讀寫gzip文檔

130.FilelnputStreamfin=newFilelnputStream(FILENAME);

131.GZIPInputStreamgzis=newGZIPInputStream(fin);

132.InputStreamReaderxover=newInputStreamReader(gzis);

133.BufferedReaderis=newBufferedReader(xover);

134.Stringline;

135.while((line=is.readLine0)!=null)

136.System.out.printIn(,zRead:〃+line);

11.目錄和文件操作

Java代碼

1.//獲取文件信息

2.exists0:如果文件存在,返回true

3.getCanonicalPath():獲取全名

4.getNameO:文件名

5.getParent():父目錄

6.canRead():如果文件可讀,返回true

7.canWrite():如果文件可寫,返回true

8.lastModifiedO:文件更新時(shí)間

9.length():文件大小

10.isFileO:如果是文件,返回true

11.ifDirectory():如果是目錄,返回true

12.要調(diào)用文件的這些方法,必須

13.Filef=newFile(fileName);

14.

15.//創(chuàng)建文件

16.Filef=newFile(,,c:\\test\\mytest.txtz,);

17.f.createNewFile();//創(chuàng)建mytest.txt文件到test目錄下

18.

19.//修改文件名

20.Filef=newFile(/Zc:\\test\\mytest.txt");

21.f.renameTo(newFileCc:\\test\\google.txt"));

22.把mytest.txt修改成google,txt

23.

24.//刪除文件

25.Filef=newFile("c:\\test\\mytest.txt");

26.f.delete();

27.

28.//臨時(shí)文件

29.Filef=newFile('C:\\test");//指定一個(gè)文件夾

30.//在test文件夾中創(chuàng)建foo前綴,tmp后綴的臨時(shí)文件

31.Filetmp=File.createTempFile("foo","tmp”,f):

32.tmp.deleteOnExitO;//在程序結(jié)束時(shí)刪除該臨時(shí)文件

33.

34.//更改文件屬性

35.setReadOnly():設(shè)置為只讀

36.setlastModified():設(shè)置最后更改時(shí)間

37.

38.//列出當(dāng)前文件夾的文件列表

39.String[]dir=newjava.io.Filelist。;

40.java.util.Arrays,sort(dir);

41.for(inti=0;i<dir.length;i++){

42.System,out.println(dir[i]);

43.)

44.

45.//過濾文件列表

46.classOnlyJavaimplementsFilenameFilter(

47.publicbooleanaccept(Filedir,Strings){

48.if(s.endsWith(".java")||s.endsWith(".clas

s")||s.endsWith(".jar"))

49.returntrue;

50.)

51.)

52.

53.//獲取根目錄

54.File口rootDir=File.listRoots();

55.for(inti=0;i<rootDir.length;i++){

56.System,out.printin(rootDir[i]);

57.)

58.

59.//創(chuàng)建新目錄

60.newFile(z//home/ian/bin,z).mkdir();//如果”/home/ian”存在,

則可以創(chuàng)建bin目錄

61.newFile("/home/ian/bin").mkdirs。;//如果“/home/ian”不存

在,會(huì)創(chuàng)建所有的目錄

12.國(guó)際化和本地化

Java代碼

1.//H8N資源

2.ResourceBundlerb=ResourceBundle.getBundle(^Menus^);

3.Stringlabel=rb.getString(z,exit.label,/);

4.//ResourceBundle相當(dāng)于名值對(duì),獲取Menus按鈕的區(qū)域?qū)傩?/p>

5.Menus_cn.properties:不同區(qū)域的屬性文件

6.

7.//列出有效區(qū)域

8.Locale1]list=Locale.getAvailableLocales();

9.

10.//指定區(qū)域

11.LocalecnLocale=Locale.CHINA;

12.

13.//設(shè)置默認(rèn)區(qū)域

14.Locale.setDefault(Locale.CHINA);

15.

16.//格式化消息

17.publicclassMessageFormatDemo{

18.staticObject[]data={

19.newjava.util.DateO,

20.“myfile.txt〃,

21.“couldntobeopened”

22.);

23.publicstaticvoidmain(String[]args){

24.Stringresult=MessageFormat.format(,zAt{0

,time}on{0,date},{1}{2}.〃,data);

25.System,out.printin(result);

26.)

27.}

28.輸

出:At10:10:08on2009-6-18,myfile.txtcouldntobe

opened.

29.

30.//從資源文件中讀消息

31.Widgets,properties在com.sean.cook,chap11下

32.ResourceBundlerb=ResourceBundle.getBundle(^com.sean.cook,

chap11.Widgets");

33.Stringpropt=rb.getStringC^filedialogs.cantopen,string");

34.Stringresult=MessageFormat.format(rb.getStringC^filedialo

gs.cantopen,format"),data);

13.網(wǎng)絡(luò)客戶端

Java代碼

1.//訪問服務(wù)器

2.Socketsocket=newSocket(〃127.0.0.1〃,8080);

3.//todosomething

4.socket,close();

5.

6.//查找網(wǎng)絡(luò)地址

7.InetAddress.getByName(hostName).getHostAddress());//根據(jù)主

機(jī)名得到IP地址

8.InetAddress.getByName(ipAddr).getHostName());//根據(jù)IP地址

得到主機(jī)名

9.

10.//連接具體異常

11.UnknownHostException

12.NoRouteToHostException

13.ConnectException

14.

15.//Socket讀寫文本數(shù)據(jù)

16.BufferedReaderin=newBufferedReader(newInputStreamRead

er(socket,getInputStream()));

17.StringremoteTime=in.readline();

18.PrintWriterout=newPrintWriter(socket.getOutputStream(),

true);

19.out.print(z,sendmessagetoclient\r\n〃);

20.out.flush();

21.

22.//Socket讀寫二進(jìn)制數(shù)據(jù)

23.DatalnputStreamin=newDatalnputStream(newBufferedlnput

Stream(socket,getInputStream()));

24.longremoteTime=(long)(in.readUnsignedByte()?24);

25.DataOutputStreamout=newDataOutputStream(socket.getOutpu

tStreamO,true);

26.

27.//Socket讀寫串行化數(shù)據(jù)

28.ObjectlnputStreamin=newObjectInputStream(newBufferedl

nputStream(socket,getInputStream()));

29.Objecto=in.readObject();

30.if(oinstanceofDate)//驗(yàn)證對(duì)象類型

31.ObjectOutputStreamout=newObjectOutputStream(socket.getO

utputStreamO,true);

32.

33.//UDP數(shù)據(jù)報(bào)

34.privatefinalstaticintPACKET_SIZE=1024;

35.

36.Stringhost=〃EV001B389673DE〃;

37.InetAddressserverAddr=InetAddress.getByName(host);

38.DatagramSocketsocket=newDatagramSocket();

39.byte[]buffer=newbyte[PACKET_SIZE];//分配數(shù)據(jù)緩沖空

40.DatagramPacketpacket=newDatagramPacket(buffer,PACKET_

SIZE,serverAddr,8080);

41.packet.setLength(PACKET_SIZE-1);//設(shè)置數(shù)據(jù)長(zhǎng)度

42.socket,send(packet);

43.socket,receive(packet);//接收數(shù)據(jù)

14.服務(wù)器端:Socket

Java代碼

1.//創(chuàng)建ServerSocket

2.ServerSocketserverSocket;

3.SocketclientSocket;

4.

5.serverSocket=newServerSocket(9999);

6.while((clientSocket=serverSocket.accept())!=null){

7.System,out.println(zzAcceptfromclient"+s.getln

etAddressO);

8.s.close();

9.)

10.

11.//監(jiān)聽內(nèi)部網(wǎng)

12.publicstaticfinalshortPORT=9999;

13.publicstaticfinalStringINSIDEJ10ST="acmewidgets-ins

ide";//網(wǎng)絡(luò)接口名

14.publicstaticfinalintBACKLOG=10;//待發(fā)數(shù)

15.serverSocket=newServerSocket(PORT,BACKLOG,InetAddress

.getByName(INSIDE_HOST));

16.

17.//返回相應(yīng)對(duì)象

18.ServerSocketserverSocket=newServerSocket(9999);;

19.SocketclientSocket;

20.BufferedReaderin=null;

21.PrintWriterout=null;

22.while(true){

23.clientSocket=serverSocket.accept();

24.in=newBufferedReader(newInputStreamReader(clien

tSocket.getlnputStreamO,〃8859_1"));

25.out=newPrintWriter(newOutputStreamWriter(client

Socket.getOutputStream(),“8859」〃),true);

26.StringechoLine;

27.while((echoLine=in.readLine())!=null){

28.System,out.printinC'Read〃+echoLine);

29.out.print(echoLine+〃\r\n〃);

30.)

31.}

32.以上例子返回字符串,如果返回二進(jìn)制,則使用DataOutputStream;返

回對(duì)象,使用ObjectOutputStream

33.

34.//處理多客戶端

35.需要把接收數(shù)據(jù)的處理放入多線程中

36.publicclassEchoServerThreaded{

37.publicstaticfinalintECHOPORT=7;

38.publicstaticfinalintNUM_THREADS=4;

39.

40.publicstaticvoidmain(String[]av){

41.newEchoServerThreaded(ECHOPORT,NUM_THREADS)

T

42.)

43.

44.publicEchoServerThreaded2(intport,intnumThreads

)(

45.ServerSocketservSock;

46.SocketclientSocket;

47.try(

48.servSock=newServerSocket(ECHOPORT

);

49.}catch(lOExceptione){

50.thrownewRuntimeException("Couldno

tcreateServerSocket〃+e);

51.)

52.for(inti=0;i<numThreads;i++){

53.newHandler(servSock,i).start();

54.)

55.)

56.)

57.classHandlerextendsThread(

58.ServerSocketservSock;

59.intthreadNumber;

60.

61.Handler(ServerSockets3,inti){

62.super();

63.servSock=s;

64.threadNumber=i;

65.setName("Thread〃+threadNumber);

66.)

67.

68.publicvoidrun(){

69.while(true)

70.try(

71.System,out.printin(getName()+

waiting);

72.SocketclientSocket;

73.synchronized(servSock){

74.clientSocket=servSo

ck.accept();

75.)

76.System,out.printIn(getName0+

〃starting,IP=〃+clientSocket.getlnetAddress());

77.BufferedReaderis=newBuf

feredReader(newInputStreamReader(

78.clientSocket.getlnputSt

ream()));

79.PrintStreamos=newPrints

tream(clientSocket.getOutputStream(),true);

80.Stringline;

81.while((line=is.readLine()

)!=null){

82.os.print(line+〃\r\n

”);

83.os.flush();

84.)

85.System.out.printin(getName()+

ENDED〃);

86.clientSocket.close();

87.}catch(lOExceptionex){

88.System,out.printin(getName()+

〃:10Erroronsocket〃+ex);

89.return;

90.)

91.}

92.)

93.)

94.

95.//使用SSL和JSSE保護(hù)Web服務(wù)器

96.SSLServerSocketFactoryssf=(SSLServerSocketFactory)SSLServ

erSocketFactory.getDefault();

97.ServerSocketserverSocket=ssf.createServerSocket(8080);

98.

99.//Log4j

100.Level級(jí)

別:DEBUG<INFO<WARN<ERROR<FATAL<OFF

101.Appender:輸出信息

102.ConsoleAppender:輸出控制臺(tái)System,out

103.

104.//找到網(wǎng)絡(luò)接口

105.Enumerationlist=Networkinterface.getNetworklnterface

s();

106.while(list.hasMoreElements()){

107.Networkinterfaceiface=(Networkinterface)list

,nextElement();

108.System,out.println(iface.getDisplayName());

109.Enumerationaddrs=iface.getlnetAddresses();

110.while(addrs.hasMoreElements()){

111.InetAddressaddr=(InetAddress)addrs.n

extElement();

112.Syste

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論