




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
Java畢業設計外文翻譯Java畢業設計外文翻譯/Java畢業設計外文翻譯畢業設計(論文)外文文獻翻譯譯文:JavaI/O系統[]對編程語言的設計者來說,創建一套好的輸入輸出(I/O)系統,是一項難度極高的任務。這一類可以從解決方案的數量之多上看出端倪。這個問題就難在它要面對的可能性太多了。不僅是因為有那么多的I/O的源和目的(文件,控制臺,網絡連接等等),而且還有很多方法(順序的,隨機的,緩存的,二進制的,字符方式的,行的,字的等等)。Java類庫的設計者們用“創建很多類”的辦法來解決這個問題。坦率地說,JavaI/O系統的類實在太多了,以至于初看起來會把人嚇著(但是,具有諷刺意味的是,這種設計實際上是限制了類的爆炸性增長)。此外,Java在1.0版之后又對其I/O類庫進行了重大的修改,原先是面向byte的,現在又補充了面向Unicode字符的類庫。為了提高性能,完善功能,JDK1.4又加了一個nio(意思是“newI/O”。這個名字會用上很多年)。這么以來,如果你想對Java的I/O類庫有個全面了解,并且做到運用自如,你就得先學習大量的類。此外,了解I/O類庫的演化歷史也是相當重要的。可能你的第一反應是“別拿什么歷史來煩我了,告訴我怎么用就可以了!”但問題是,如果你對這段一無所知,很快就會被一些有用或是沒用的類給搞糊涂了。本文會介紹Java標準類庫中的各種I/O類,與其使用方法。File類在介紹直接從流里讀寫數據的類之前,我們先介紹一下處理文件和目錄的類。你會認為這是一個關于文件的類,但它不是。你可以用它來表示某個文件的名字,也可以用它來表示目錄里一組文件的名字。如果它表示的是一組文件,那么你還可以用list()方法來進行查詢,讓它會返回String數組。由于元素數量是固定的,因此數組會比容器更好一些。如果你想要獲取另一個目錄的清單,再建一個File對象就是了。目錄列表器假設你想看看這個目錄。有兩個辦法。一是不帶參數調用list()。它返回的是File對象所含內容的完整清單。但是,如果你要的是一個"限制性列表(restrictedlist)"的話——比方說,你想看看所有擴展名為.java的文件——那么你就得使用"目錄過濾器"了。這是一個專門負責挑選顯示File對象的內容的類。FilenameFilter接口的聲明:publicinterfaceFilenameFilter{booleanaccept(Filedir,Stringname);}accept()方法需要兩個參數,一個是File對象,表示這個文件是在哪個目錄里面的;另一個是String,表示文件名。雖然你可以忽略它們中的一個,甚至兩個都不管,但是你大概總得用一下文件名吧。記住,list()會對目錄里的每個文件調用accept(),并以此判斷是不是把它包括到返回值里;這個判斷依據就是accept()的返回值。切記,文件名里不能有路徑信息。為此你只要用一個String對象來創建File對象,然后再調用這個File對象的getName()就可以了。它會幫你剝離路徑信息(以一種平臺無關的方式)。然后再在accept()里面用正則表達式(regularexpression)的matcher對象判斷,regex是否與文件名相匹配。兜完這個圈子,list()方法返回了一個數組。匿名內部類這是用匿名內部類來征程程序的絕佳機會。下面我們先創建一個返回FilenameFileter的filter()方法。//Usesanonymousinnerclasses.importjava.io.*;importjava.util.*;importcom.bruceeckel.util.*;publicclassDirList2{publicstaticFilenameFilterfilter(finalStringafn){//Creationofanonymousinnerclass:returnnewFilenameFilter(){Stringfn=afn;publicbooleanaccept(Filedir,Stringn){//Strippathinformation:Stringf=newFile(n).getName();returnf.indexOf(fn)!=-1;}};//Endofanonymousinnerclass}publicstaticvoidmain(String[]args){Filepath=newFile(".");String[]list;if(args.length==0)list=path.list();elselist=path.list(filter(args[0]));Arrays.sort(list,newAlphabeticComparator());for(inti=0;i<list.length;i++)System.out.println(list[i]);}}注意,filter()的參數必須是final的。要想在匿名內部類里使用其作用域之外的對象,只能這么做。這是對前面所講的代碼的改進,現在FilenameFilter類已經與DirList2緊緊地綁在一起了。不過你還可以更進一步,把這個匿名內部類定義成list()的參數,這樣代碼會變得更緊湊://Buildingtheanonymousinnerclass"in-place."importjava.io.*;importjava.util.*;importcom.bruceeckel.util.*;publicclassDirList3{publicstaticvoidmain(finalString[]args){Filepath=newFile(".");String[]list;if(args.length==0)list=path.list();elselist=path.list(newFilenameFilter(){publicbooleanaccept(Filedir,Stringn){Stringf=newFile(n).getName();returnf.indexOf(args[0])!=-1;}});Arrays.sort(list,newAlphabeticComparator());for(inti=0;i<list.length;i++)System.out.println(list[i]);}}現在該輪到main()的參數成final了,因為匿名內部類要用它的arg[0].這個例子告訴我們,可以用匿名內部類來創建專門供特定問題用的,一次性的類。這種做法的好處是,它能把解決某個問題的代碼全部集中到一個地方。但是從另一角度來說,這樣做會使代碼的可讀性變差,所以要慎重。查看與創建目錄File類的功能不僅限于顯示文件或目錄。它還能幫你創建新的目錄甚至是目錄路徑(directorypath),如果目錄不存在的話。此外它還能用來檢查文件的屬性(大小,上次修改的日期,讀寫權限等),判斷File對象表示的是文件還是目錄,以與刪除文件。renameTo()這個方法會把文件重命名成(或者說移動到)新的目錄,也就是參數所給出的目錄。而參數本身就是一個File對象。這個方法也適用于目錄。輸入與輸出I/O類庫常使用"流(stream)"這種抽象。所謂"流"是一種能生成或接受數據的,代表數據的源和目標的對象。流把I/O設備內部的具體操作給隱藏起來了。正如JDK文檔所示的,Java的I/O類庫分成輸入和輸出兩大部分。所有InputStream和Reader的派生類都有一個基本的,繼承下來的,能讀取單個或byte數組的read()方法。同理,所有OutputStream和Writer的派生類都有一個基本的,能寫入單個或byte數組的write()方法。但通常情況下,你是不會去用這些方法的;它們是給其它類用的——而后者會提供一些更實用的接口。因此,你很少會碰到只用一個類就能創建一個流的情形,實際上你得把多個對象疊起來,并以此來獲取所需的功能。Java的流類庫之所以會那么讓人犯暈,最主要的原因就是"你必須為創建一個流而動用多個對象"。我們最好還是根據其功能為這些class歸個類。Java1.0的類庫設計者們是從決定“讓所有與輸入相關的類去繼承InputStream”入手的。同理,所有與輸出相關的類就該繼承OutputStream了。添加屬性與適用的接口使用"分層對象(layeredobjects)",為單個對象動態地,透明地添加功能的做法,被稱為DecoratorPattern。(模式是ThinkinginPatterns(withJava)的主題。)Decorator模式要求所有包覆在原始對象之外的對象,都必須具有與之完全相同的接口。這使得decorator的用法變得非常的透明--無論對象是否被decorate過,傳給它的消息總是相同的。這也是JavaI/O類庫要有"filter(過濾器)"類的原因:抽象的"filter"類是所有decorator的基類。(decorator必須具有與它要包裝的對象的全部接口,但是decorator可以擴展這個接口,由此就衍生出了很多"filter"類)。Decorator模式常用于如下的情形:如果用繼承來解決各種需求的話,類的數量會多到不切實際的地步。Java的I/O類庫需要提供很多功能的組合,于是decorator模式就有了用武之地。但是decorator有個缺點,在提高編程的靈活性的同時(因為你能很容易地混合和匹配屬性),也使代碼變得更復雜了。Java的I/O類庫之所以會這么怪,就是因為它"必須為一個I/O對象創建很多類",也就是為一個"核心"I/O類加上很多decorator。為InputStream和OutputStream定義decorator類接口的類,分別是FilterInputStream和FilterOutputStream。這兩個名字都起得不怎么樣。FilterInputStream和FilterOutputStream都繼承自I/O類庫的基類InputStream和OutputStream,這是decorator模式的關鍵(惟有這樣decorator類的接口才能與它要服務的對象的完全相同)。用FilterInputStream讀取InputStreamFilterInputStream與其派生類有兩項重要任務。DataInputStream可以讀取各種primitive與String。(所有的方法都以"read"打頭,比如readByte(),readFloat())。它,以與它的搭檔DataOutputStream,能讓你通過流將primitive數據從一個地方導到另一個地方。這些"地方"都列在表12-4里。其它的類都是用來修改InputStream的內部行為的:是不是做緩沖,是不是知道它所讀取的行信息(允許你讀取行號或設定行號),是不是會彈出單個字符。后兩個看上去更像是給編譯器用的(也就是說,它們大概是為Java編譯器設計的),所以通常情況下,你是不大會用到它們的。不論你用哪種I/O設備,輸入的時候,最好都做緩沖。所以對I/O類庫來說,比較明智的做法還是把不緩沖當特例(或者去直接調用方法),而不是像現在這樣把緩沖當作特例。外文原文:JAVAI/OSystemCreatingagoodinput/output(I/O)systemisoneofthemoredifficulttasksforthelanguagedesigner.Thisisevidencedbythenumberofdifferentapproaches.Thechallengeseemstobeincoveringalleventualities.NotonlyaretheredifferentsourcesandsinksofI/Othatyouwanttocommunicatewith(files,theconsole,networkconnections),butyouneedtotalktotheminawidevarietyofways(sequential,random-access,buffered,binary,character,bylines,bywords,etc.).TheJavalibrarydesignersattackedthisproblembycreatinglotsofclasses.Infact,therearesomanyclassesforJava’sI/Osystemthatitcanbeintimidatingatfirst(ironically,theJavaI/Odesignactuallypreventsanexplosionofclasses).TherewasalsoasignificantchangeintheI/OlibraryafterJava1.0,whentheoriginalbyte-orientedlibrarywassupplementedwithchar-oriented,Unicode-basedI/Oclasses.AsaresultthereareafairnumberofclassestolearnbeforeyouunderstandenoughofJava’sI/Opicturethatyoucanuseitproperly.Inaddition,it’sratherimportanttounderstandtheevolutionhistoryoftheI/Olibrary,evenifyourfirstreactionis“don’tbothermewithhistory,justshowmehowtouseit!”Theproblemisthatwithoutthehistoricalperspectiveyouwillrapidlybecomeconfusedwithsomeoftheclassesandwhenyoushouldandshouldn’tusethem.ThisarticlewillgiveyouanintroductiontothevarietyofI/OclassesinthestandardJavalibraryandhowtousethem.TheFileclassBeforegettingintotheclassesthatactuallyreadandwritedatatostreams,we’lllookautilityprovidedwiththelibrarytoassistyouinhandlingfiledirectoryissues.TheFileclasshasadeceivingname—youmightthinkitreferstoafile,butitdoesn’t.Itcanrepresenteitherthenameofaparticularfileorthenamesofasetoffilesinadirectory.Ifit’sasetoffiles,youcanaskforthesetwiththelist(
)method,andthisreturnsanarrayofString.Itmakessensetoreturnanarrayratherthanoneoftheflexiblecontainerclassesbecausethenumberofelementsisfixed,andifyouwantadifferentdirectorylistingyoujustcreateadifferentFileobject.Infact,“FilePath”wouldhavebeenabetternamefortheclass.Thissectionshowsanexampleoftheuseofthisclass,includingtheassociatedFilenameFilterinterface.AdirectorylisterSupposeyou’dliketoseeadirectorylisting.TheFileobjectcanbelistedintwoways.Ifyoucalllist(
)withnoarguments,you’llgetthefulllistthattheFileobjectcontains.However,ifyouwantarestrictedlist—forexample,ifyouwantallofthefileswithanextensionof.java—thenyouusea“directoryfilter,”whichisaclassthattellshowtoselecttheFileobjectsfordisplay.TheDirFilterclass“implements”theinterfaceFilenameFilter.It’susefultoseehowsimpletheFilenameFilterinterfaceis:publicinterfaceFilenameFilter{booleanaccept(Filedir,Stringname);}Theaccept(
)methodmustacceptaFileobjectrepresentingthedirectorythataparticularfileisfoundin,andaStringcontainingthenameofthatfile.Youmightchoosetouseorignoreeitherofthesearguments,butyouwillprobablyatleastusethefilename.Rememberthatthelist(
)methodiscallingaccept(
)foreachofthefilenamesinthedirectoryobjecttoseewhichoneshouldbeincluded—thisisindicatedbythebooleanresultreturnedbyaccept(
).Tomakesuretheelementyou’reworkingwithisonlythefilenameandcontainsnopathinformation,allyouhavetodoistaketheStringobjectandcreateaFileobjectoutofit,thencallgetName(
),whichstripsawayallthepathinformation(inaplatform-independentway).Thenaccept(
)usesthearegularexpressionmatcherobjecttoseeiftheregularexpressionregexmatchesthenameofthefile.Usingaccept(),thelist()methodreturnsanarray.AnonymousinnerclassesThisexampleisidealforrewritingusingananonymousinnerclass.Asafirstcut,amethodfilter(
)iscreatedthatreturnsareferencetoaFilenameFilter://Usesanonymousinnerclasses.importjava.io.*;importjava.util.*;importcom.bruceeckel.util.*;publicclassDirList2{publicstaticFilenameFilterfilter(finalStringafn){//Creationofanonymousinnerclass:returnnewFilenameFilter(){Stringfn=afn;publicbooleanaccept(Filedir,Stringn){//Strippathinformation:Stringf=newFile(n).getName();returnf.indexOf(fn)!=-1;}};//Endofanonymousinnerclass}publicstaticvoidmain(String[]args){Filepath=newFile(".");String[]list;if(args.length==0)list=path.list();elselist=path.list(filter(args[0]));Arrays.sort(list,newAlphabeticComparator());for(inti=0;i<list.length;i++)System.out.println(list[i]);}}Notethattheargumenttofilter(
)mustbefinal.Thisisrequiredbytheanonymousinnerclasssothatitcanuseanobjectfromoutsideitsscope.ThisdesignisanimprovementbecausetheFilenameFilterclassisnowtightlyboundtoDirList2.However,youcantakethisapproachonestepfurtheranddefinetheanonymousinnerclassasanargumenttolist(
),inwhichcaseit’sevensmaller://Buildingtheanonymousinnerclass"in-place."importjava.io.*;importjava.util.*;importcom.bruceeckel.util.*;publicclassDirList3{publicstaticvoidmain(finalString[]args){Filepath=newFile(".");String[]list;if(args.length==0)list=path.list();elselist=path.list(newFilenameFilter(){publicbooleanaccept(Filedir,Stringn){Stringf=newFile(n).getName();returnf.indexOf(args[0])!=-1;}});Arrays.sort(list,newAlphabeticComparator());for(inti=0;i<list.length;i++)System.out.println(list[i]);}}Theargumenttomain(
)isnowfinal,sincetheanonymousinnerclassusesargs[0]directly.Thisshowsyouhowanonymousinnerclassesallowthecreationofquick-and-dirtyclassestosolveproblems.SinceeverythinginJavarevolvesaroundclasses,thiscanbeausefulcodingtechnique.Onebenefitisthatitkeepsthecodethatsolvesaparticularproblemisolatedtogetherinonespot.Ontheotherhand,itisnotalwaysaseasytoread,soyoumustuseitjudiciously.CheckingforandcreatingdirectoriesTheFileclassismorethanjustarepresentationforanexistingfileordirectory.YoucanalsouseaFileobjecttocreateanewdirectoryoranentiredirectorypathifitdoesn’texist.Youcanalsolookatthecharacteristicsoffiles(size,lastmodificationdate,read/write),seewhetheraFileobjectrepresentsafileoradirectory,anddeleteafile.Thefirstmethodthat’sexercisedbymain(
)isrenameTo(
),whichallowsyoutorename(ormove)afiletoanentirelynewpathrepresentedbytheargument,whichisanotherFileobject.Thisalsoworkswithdirectoriesofanylength.InputandoutputI/Olibrariesoftenusetheabstractionofastream,whichrepresentsanydatasourceorsinkasanobjectcapableofproducingorreceivingpiecesofdata.ThestreamhidesthedetailsofwhathappenstothedatainsidetheactualI/Odevice.TheJavalibraryclassesforI/Oaredividedbyinputandoutput,asyoucanseebylookingattheonlineJavaclasshierarchyintheJDKdocumentation.Byinheritance,everythingderivedfromtheInputStreamorReaderclasseshavebasicmethodscalledread(
)forreadingasinglebyteorarrayofbytes.Likewise,everythingderivedfromOutputStreamorWriterclasseshavebasicmethodscalledwrite(
)forwritingasinglebyteorarrayofbytes.However,youwon’tgenerallyusethesemethods;theyexistsothatotherclassescanusethem—theseotherclassesprovideamoreusefulinterface.Thus,you’llrarelycreateyourstreamobjectbyusingasingleclass,butinsteadwilllayermultipleobjectstogethertoprovideyourdesiredfunctionality.ThefactthatyoucreatemorethanoneobjecttocreateasingleresultingstreamistheprimaryreasonthatJava’sstreamlibraryisconfusing.It’shelpfultocategorizetheclassesbytheirfunctionality.InJava1.0,thelibrarydesignersstartedbydecidingthatallclassesthathadanythingtodowithinputwouldbeinheritedfromInputStreamandallclassesthatwereassociatedwithoutputwouldbeinheritedfromOutputStream.AddingattributesandusefulinterfacesTheuseoflayeredobjectstodynamicallyandtransparentlyaddresponsibilitiestoindividualobjectsisreferredtoastheDecoratorpattern.Thedecoratorpatternspecifiesthatallobjectsthatwraparoundyourinitialobjecthavethesameinterface.Thismakesthebasicuseofthedecoratorstransparent—yousendthesamemessagetoanobjectwhetherit’sbeendecoratedornot.Thisisthereasonfortheexistenceofthe“filter”classesintheJavaI/Olibrary:theabstract“filter”classisthebaseclassforallthedecorators.(Adecoratormusthavethesameinterfaceastheobjectitdecorates,butthedecoratorcanalsoextendtheinterface,whichoccursinseveralofthe“filter”classes).Decoratorsareoftenusedwhensimplesubclassingresultsinalargenumberofsubclassesinordertosatisfyeverypossiblecombinationthatisneeded—somanysubclassesthatitbecomesimpractical.TheJavaI/Olibraryrequiresmanydifferentcombinationsoffeatures,whichiswhythedecoratorpatternisused.Thereisadrawbacktothedecoratorpattern,however.Decoratorsgiveyoumuchmoreflexibilitywhileyou’rewritingaprogram(sinceyoucaneasilymixandmatchattributes),buttheyaddcomplexitytoyourcode.ThereasonthattheJavaI/Olibraryisawkwardtouseisthatyoumustcreatemanyclasses—the“core”I/Otypeplusallthedecorators—inordertogetthesingleI/Oobjectthatyouwant.Theclassesthatprovidethedecoratorinterfacetocont
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 金卡委托加工協議書
- 裝飾設計掛靠協議書
- 涉外招生協議書范本
- 陜西日報新浪協議書
- 投票參賽協議書范本
- 威寧異地搬遷協議書
- 宿舍用電防火協議書
- 田間播種協議書范本
- 污水安全生產協議書
- 主體鋼筋承包協議書
- 礦石采購合同范本
- 2024年甘肅省煙草專賣局招聘考試真題
- 2025年龍江森工集團權屬林業局有限公司招聘筆試參考題庫含答案解析
- (二模)溫州市2025屆高三第二次適應性考試英語試卷(含答案)+聽力音頻+聽力原文
- DeepSeek+AI組合精準賦能教師教學能力進階實戰 課件 (圖片版)
- 2025年纖維檢驗員(高級)職業技能鑒定參考試題庫(含答案)
- 調試報告-交換機
- 屋面防水施工技術PPT (2020,44P)
- 鐵路隧道出口支護、仰拱、防排水首件評估監理總結
- 關于無行賄犯罪行為記錄的承諾書
- 防城港職業技術學院籌設實施方案
評論
0/150
提交評論