Tải bản đầy đủ (.pdf) (2,330 trang)

Prentice hall core java volume 2 advanced features 8th edition apr 2008 ISBN 0132354799

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (13.43 MB, 2,330 trang )

CoreJava™VolumeII–AdvancedFeatures,
EighthEdition
byCayS.Horstmann;GaryCornell
Publisher:PrenticeHall
PubDate:April08,2008
PrintISBN-10:0-13-235479-9
PrintISBN-13:978-0-13-235479-0
eTextISBN-10:0-13-714448-2
eTextISBN-13:978-0-13-714448-8
Pages:1056
TableofContents|Index

Overview
TherevisededitionoftheclassicCoreJava™,VolumeII—
AdvancedFeatures,coversadvanceduser-interface
programmingandtheenterprisefeaturesoftheJavaSE6
platform.LikeVolumeI(whichcoversthecorelanguageand
libraryfeatures),thisvolumehasbeenupdatedforJavaSE6
andnewcoverageishighlightedthroughout.Allsample
programshavebeencarefullycraftedtoillustratethelatest
programmingtechniques,displayingbest-practicessolutionsto
thetypesofreal-worldproblemsprofessionaldevelopers
encounter.
VolumeIIincludesnewsectionsontheStAXAPI,JDBC4,
compilerAPI,scriptingframework,splashscreenandtrayAPIs,
andmanyotherJavaSE6enhancements.Inthisbook,the
authorsfocusonthemoreadvancedfeaturesoftheJava
language,includingcompletecoverageof
StreamsandFiles
Networking
Databaseprogramming




XML
JNDIandLDAP
Internationalization
AdvancedGUIcomponents
Java2DandadvancedAWT
JavaBeans
Security
RMIandWebservices
Collections
Annotations
Nativemethods
ForthoroughcoverageofJavafundamentals—including
interfacesandinnerclasses,GUIprogrammingwithSwing,
exceptionhandling,generics,collections,andconcurrency—look
fortheeightheditionofCoreJava™,VolumeI—Fundamentals
(ISBN:978-0-13-235476-9).


CoreJava™VolumeII–AdvancedFeatures,
EighthEdition
byCayS.Horstmann;GaryCornell
Publisher:PrenticeHall
PubDate:April08,2008
PrintISBN-10:0-13-235479-9
PrintISBN-13:978-0-13-235479-0
eTextISBN-10:0-13-714448-2
eTextISBN-13:978-0-13-714448-8
Pages:1056

TableofContents|Index

Copyright
Preface
Acknowledgments
Chapter1.StreamsandFiles
Streams
TextInputandOutput
ReadingandWritingBinaryData
ZIPArchives
ObjectStreamsandSerialization
FileManagement
NewI/O
RegularExpressions
Chapter2.XML
IntroducingXML
ParsinganXMLDocument
ValidatingXMLDocuments
LocatingInformationwithXPath
UsingNamespaces
StreamingParsers


GeneratingXMLDocuments
XSLTransformations
Chapter3.Networking
ConnectingtoaServer
ImplementingServers
InterruptibleSockets
SendingE-Mail

MakingURLConnections
Chapter4.DatabaseProgramming
TheDesignofJDBC
TheStructuredQueryLanguage
JDBCConfiguration
ExecutingSQLStatements
QueryExecution
ScrollableandUpdatableResultSets
RowSets
Metadata
Transactions
ConnectionManagementinWebandEnterpriseApplications
IntroductiontoLDAP
Chapter5.Internationalization
Locales
NumberFormats
DateandTime
Collation
MessageFormatting
TextFilesandCharacterSets
ResourceBundles
ACompleteExample
Chapter6.AdvancedSwing
Lists
Tables


Trees
TextComponents
ProgressIndicators

ComponentOrganizers
Chapter7.AdvancedAWT
TheRenderingPipeline
Shapes
Areas
Strokes
Paint
CoordinateTransformations
Clipping
TransparencyandComposition
RenderingHints
ReadersandWritersforImages
ImageManipulation
Printing
TheClipboard
DragandDrop
PlatformIntegration
Chapter8.JavaBeansComponents
WhyBeans?
TheBean-WritingProcess
UsingBeanstoBuildanApplication
NamingPatternsforBeanPropertiesandEvents
BeanPropertyTypes
BeanInfoClasses
PropertyEditors
Customizers
JavaBeansPersistence
Chapter9.Security
ClassLoaders



BytecodeVerification
SecurityManagersandPermissions
UserAuthentication
DigitalSignatures
CodeSigning
Encryption
Chapter10.DistributedObjects
TheRolesofClientandServer
RemoteMethodCalls
TheRMIProgrammingModel
ParametersandReturnValuesinRemoteMethods
RemoteObjectActivation
WebServicesandJAX-WS
Chapter11.Scripting,Compiling,andAnnotationProcessing
ScriptingfortheJavaPlatform
TheCompilerAPI
UsingAnnotations
AnnotationSyntax
StandardAnnotations
Source-LevelAnnotationProcessing
BytecodeEngineering
Chapter12.NativeMethods
CallingaCFunctionfromaJavaProgram
NumericParametersandReturnValues
StringParameters
AccessingFields
EncodingSignatures
CallingJavaMethods
AccessingArrayElements

HandlingErrors
UsingtheInvocationAPI
ACompleteExample:AccessingtheWindowsRegistry


Index


Copyright
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andthepublisherwas
awareofatrademarkclaim,thedesignationshavebeenprinted
withinitialcapitallettersorinallcapitals.
SunMicrosystems,Inc.,hasintellectualpropertyrightsrelating
toimplementationsofthetechnologydescribedinthis
publication.Inparticular,andwithoutlimitation,these
intellectualpropertyrightsmayincludeoneormoreU.S.
patents,foreignpatents,orpendingapplications.Sun,Sun
Microsystems,theSunlogo,J2ME,Solaris,Java,Javadoc,
NetBeans,andallSunandJavabasedtrademarksandlogosare
trademarksorregisteredtrademarksofSunMicrosystems,Inc.,
intheUnitedStatesandothercountries.UNIXisaregistered
trademarkintheUnitedStatesandothercountries,exclusively
licensedthroughX/OpenCompany,Ltd.
Theauthorsandpublisherhavetakencareinthepreparationof
thisbook,butmakenoexpressedorimpliedwarrantyofany
kindandassumenoresponsibilityforerrorsoromissions.No
liabilityisassumedforincidentalorconsequentialdamagesin
connectionwithorarisingoutoftheuseoftheinformationor

programscontainedherein.
THISPUBLICATIONISPROVIDED"ASIS"WITHOUTWARRANTY
OFANYKIND,EITHEREXPRESSORIMPLIED,INCLUDING,BUT
NOTLIMITEDTO,THEIMPLIEDWARRANTIESOF
MERCHANTABILITY,FITNESSFORAPARTICULARPURPOSE,OR
NON-INFRINGEMENT.THISPUBLICATIONCOULDINCLUDE
TECHNICALINACCURACIESORTYPO-GRAPHICALERRORS.
CHANGESAREPERIODICALLYADDEDTOTHEINFORMATION
HEREIN;THESECHANGESWILLBEINCORPORATEDINNEW
EDITIONSOFTHEPUBLICATION.SUNMICROSYSTEMS,INC.,
MAYMAKEIMPROVEMENTSAND/ORCHANGESINTHE
PRODUCT(S)AND/ORTHEPROGRAM(S)DESCRIBEDINTHIS


PUBLICATIONATANYTIME.
Thepublisheroffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales,which
mayincludeelectronicversionsand/orcustomcoversand
contentparticulartoyourbusiness,traininggoals,marketing
focus,andbrandinginterests.Formoreinformation,please
contact:U.S.CorporateandGovernmentSales,(800)3823419,Forsalesoutsidethe
UnitedStatespleasecontact:InternationalSales,

VisitusontheWeb:informit.com/ph
LibraryofCongressCataloging-in-PublicationData
Horstmann,CayS.,1959CoreJava.Volume1,Fundamentals/CayS.Horstmann,GaryCornell.—
8thed.
p.cm.
Includesindex.
ISBN978-0-13-2354769(pbk.:alk.paper)1.Java(Computerprogram

language)I.Cornell,Gary.II.Title.III.Title:Fundamentals.IV.
Title:CoreJavafundamentals.
QA76.73.J38H67532008
005.13'3—dc22
2007028843
Copyright©2008SunMicrosystems,Inc.
4150NetworkCircle,SantaClara,California95054U.S.A.
Allrightsreserved.PrintedintheUnitedStatesofAmerica.This
publicationisprotectedbycopyright,andpermissionmustbe
obtainedfromthepublisherpriortoanyprohibited
reproduction,storageinaretrievalsystem,ortransmissionin
anyformorbyanymeans,electronic,mechanical,
photocopying,recording,orlikewise.Forinformationregarding


permissions,writeto:PearsonEducation,Inc.,Rightsand
ContractsDepartment,501BoylstonStreet,Suite900,Boston,
MA02116,Fax:617-671-3447.
ISBN-13:978-0-13-235479-0
TextprintedintheUnitedStatesonrecycledpaperatCourierin
Stoughton,Massachusetts.
Firstprinting,April2008


Preface
TotheReader
Thebookyouhaveinyourhandsisthesecondvolumeofthe
eightheditionofCoreJava™,fullyupdatedforJavaSE6.The
firstvolumecoverstheessentialfeaturesofthelanguage;this
volumecoverstheadvancedtopicsthataprogrammerwillneed

toknowforprofessionalsoftwaredevelopment.Thus,aswith
thefirstvolumeandthepreviouseditionsofthisbook,weare
stilltargetingprogrammerswhowanttoputJavatechnologyto
workonrealprojects.
Pleasenote:Ifyouareanexperienceddeveloperwhois
comfortablewithadvancedlanguagefeaturessuchasinner
classesandgenerics,youneednothavereadthefirstvolume
inordertobenefitfromthisvolume.Whilewedoreferto
sectionsofthepreviousvolumewhenappropriate(and,of
course,hopeyouwillbuyorhaveboughtVolumeI),youcan
findtheneededbackgroundmaterialinanycomprehensive
introductorybookabouttheJavaplatform.
Finally,whenanybookisbeingwritten,errorsandinaccuracies
areinevitable.Wewouldverymuchliketohearaboutthem
shouldyoufindanyinthisbook.Ofcourse,wewouldpreferto
hearaboutthemonlyonce.Forthisreason,wehaveputupa
websiteatwithanFAQ,bug
fixes,andworkarounds.Strategicallyplacedattheendofthe
bugreportwebpage(toencourageyoutoreadtheprevious
reports)isaformthatyoucanusetoreportbugsorproblems
andtosendsuggestionsforimprovementstofutureeditions.

AboutThisBook
Thechaptersinthisbookare,forthemostpart,independentof
eachother.Youshouldbeabletodelveintowhatevertopic
interestsyouthemostandreadthechaptersinanyorder.
ThetopicofChapter1isinputandoutputhandling.InJava,all


I/Oishandledthroughso-calledstreams.Streamsletyoudeal,

inauniformmanner,withcommunicationsamongvarious
sourcesofdata,suchasfiles,networkconnections,ormemory
blocks.Weincludedetailedcoverageofthereaderandwriter
classes,whichmakeiteasytodealwithUnicode.Weshowyou
whatgoesonunderthehoodwhenyouusetheobject
serializationmechanism,whichmakessavingandloading
objectseasyandconvenient.Finally,wecoverthe"newI/O"
classes(whichwerenewwhentheywereaddedtoJavaSE1.4)
thatsupportefficientfileoperations,andtheregularexpression
library.
Chapter2coversXML.WeshowyouhowtoparseXMLfiles,
howtogenerateXML,andhowtouseXSLtransformations.As
ausefulexample,weshowyouhowtospecifythelayoutofa
SwingforminXML.Thischapterhasbeenupdatedtoinclude
theXPathAPI,whichmakes"findingneedlesinXMLhaystacks"
mucheasier.
Chapter3coversthenetworkingAPI.Javamakesit
phenomenallyeasytodocomplexnetworkprogramming.We
showyouhowtomakenetworkconnectionstoservers,howto
implementyourownservers,andhowtomakeHTTP
connections.
Chapter4coversdatabaseprogramming.Themainfocusison
JDBC,theJavadatabaseconnectivityAPIthatletsJava
programsconnecttorelationaldatabases.Weshowyouhowto
writeusefulprogramstohandlerealisticdatabasechores,using
acoresubsetoftheJDBCAPI.(Acompletetreatmentofthe
JDBCAPIwouldrequireabookalmostaslongasthisone.)We
finishthechapterwithabriefintroductionintohierarchical
databasesanddiscussJNDI(theJavaNamingandDirectory
Interface)andLDAP(theLightweightDirectoryAccess

Protocol).
Chapter5discussesafeaturethatwebelievecanonlygrowin
importance—internationalization.TheJavaprogramming
languageisoneofthefewlanguagesdesignedfromthestartto


handleUnicode,buttheinternationalizationsupportintheJava
platformgoesmuchfurther.Asaresult,youcan
internationalizeJavaapplicationssothattheynotonlycross
platformsbutcrosscountryboundariesaswell.Forexample,
weshowyouhowtowritearetirementcalculatorappletthat
useseitherEnglish,German,orChineselanguages—depending
onthelocaleofthebrowser.
Chapter6containsalltheSwingmaterialthatdidn'tmakeit
intoVolumeI,especiallytheimportantbutcomplextreeand
tablecomponents.Weshowthebasicusesofeditorpanes,the
Javaimplementationofa"multipledocument"interface,
progressindicatorsthatyouuseinmultithreadedprograms,
and"desktopintegrationfeatures"suchassplashscreensand
supportforthesystemtray.Again,wefocusonthemostuseful
constructsthatyouarelikelytoencounterinpractical
programmingbecauseanencyclopediccoverageoftheentire
Swinglibrarywouldfillseveralvolumesandwouldonlybeof
interesttodedicatedtaxonomists.
Chapter7coverstheJava2DAPI,whichyoucanusetocreate
realisticdrawingsandspecialeffects.Thechapteralsocovers
someadvancedfeaturesoftheAWT(AbstractWindowing
Toolkit)thatseemedtoospecializedforcoverageinVolumeI
butare,nonetheless,techniquesthatshouldbepartofevery
programmer'stoolkit.Thesefeaturesincludeprintingandthe

APIsforcut-and-pasteanddrag-and-drop.
Chapter8showsyouwhatyouneedtoknowaboutthe
componentAPIfortheJavaplatform—JavaBeans.Weshowyou
howtowriteyourownbeansthatotherprogrammerscan
manipulateinintegratedbuilderenvironments.Weconclude
thischapterbyshowingyouhowyoucanuseJavaBeans
persistencetostoreyourowndatainaformatthat—unlike
objectserialization—issuitableforlong-termstorage.
Chapter9takesuptheJavasecuritymodel.TheJavaplatform
wasdesignedfromthegrounduptobesecure,andthischapter
takesyouunderthehoodtoseehowthisdesignis


implemented.Weshowyouhowtowriteyourownclassloaders
andsecuritymanagersforspecial-purposeapplications.Then,
wetakeupthesecurityAPIthatallowsforsuchimportant
featuresasmessageandcodesigning,authorizationand
authentication,andencryption.Weconcludewithexamplesthat
usetheAESandRSAencryptionalgorithms.
Chapter10coversdistributedobjects.WecoverRMI(Remote
MethodInvocation)indetail.ThisAPIletsyouworkwithJava
objectsthataredistributedovermultiplemachines.Wethen
brieflydiscusswebservicesandshowyouanexampleinwhich
aJavaprogramcommunicateswiththeAmazonWebService.
Chapter11discussesthreetechniquesforprocessingcode.
ThescriptingandcompilerAPIs,introducedinJavaSE6,allow
yourprogramtocallcodeinscriptinglanguagessuchas
JavaScriptorGroovy,andtocompileJavacode.Annotations
allowyoutoaddarbitraryinformation(sometimescalled
metadata)toaJavaprogram.Weshowyouhowannotation

processorscanharvesttheseannotationsatthesourceorclass
filelevel,andhowannotationscanbeusedtoinfluencethe
behaviorofclassesatruntime.Annotationsareonlyusefulwith
tools,andwehopethatourdiscussionwillhelpyouselect
usefulannotationprocessingtoolsforyourneeds.
Chapter12takesupnativemethods,whichletyoucall
methodswrittenforaspecificmachinesuchastheMicrosoft
WindowsAPI.Obviously,thisfeatureiscontroversial:Use
nativemethods,andthecross-platformnatureoftheJava
platformvanishes.Nonetheless,everyseriousprogrammer
writingJavaapplicationsforspecificplatformsneedstoknow
thesetechniques.Attimes,youneedtoturntotheoperating
system'sAPIforyourtargetplatformwhenyouinteractwitha
deviceorservicethatisnotsupportedbytheJavaplatform.We
illustratethisbyshowingyouhowtoaccesstheregistryAPIin
WindowsfromaJavaprogram.
Asalways,allchaptershavebeencompletelyrevisedforthe
latestversionofJava.Outdatedmaterialhasbeenremoved,


andthenewAPIsofJavaSE6arecoveredindetail.

Conventions
Asiscommoninmanycomputerbooks,weusemonospace
typetorepresentcomputercode.
Note
Notesaretaggedwithacheckmarkbutton
thatlookslikethis.

Tip

Helpfultipsaretaggedwiththis
exclamationpointbutton.

Caution
Notesthatwarnofpitfallsordangerous
situationsaretaggedwithanxbutton.

C++Note
ThereareanumberofC++notesthat
explainthedifferencebetweentheJava
programminglanguageandC++.Youcan
skipthemifyouaren'tinterestedinC++.



ApplicationProgrammingInterface
TheJavaplatformcomeswithalarge
programminglibraryorApplicationProgramming
Interface(API).WhenusinganAPIcallforthe
firsttime,weaddashortsummarydescription,
taggedwithanAPIicon.Thesedescriptionsarea
bitmoreinformalbutoccasionallyalittlemore
informativethanthoseintheofficialon-lineAPI
documentation.
Programswhosesourcecodeisincludedinthe
companioncodeforthisbookarelistedas
examples;forinstance,

Listing11.1.ScriptTest.java
Youcandownloadthecompanioncodefrom

/>

Acknowledgments
Writingabookisalwaysamonumentaleffort,andrewriting
doesn'tseemtobemucheasier,especiallywithsucharapid
rateofchangeinJavatechnology.Makingabookarealitytakes
manydedicatedpeople,anditismygreatpleasureto
acknowledgethecontributionsoftheentireCoreJavateam.
AlargenumberofindividualsatPrenticeHallandSun
MicrosystemsPressprovidedvaluableassistance,butthey
managedtostaybehindthescenes.I'dlikethemalltoknow
howmuchIappreciatetheirefforts.Asalways,mywarm
thanksgotomyeditor,GregDoenchofPrenticeHall,for
steeringthebookthroughthewritingandproductionprocess,
andforallowingmetobeblissfullyunawareoftheexistenceof
allthosefolksbehindthescenes.IamgratefultoVanessa
Moorefortheexcellentproductionsupport.Mythanksalsoto
mycoauthorofearliereditions,GaryCornell,whohassince
movedontootherventures.
Thankstothemanyreadersofearliereditionswhoreported
embarrassingerrorsandmadelotsofthoughtfulsuggestions
forimprovement.Iamparticularlygratefultotheexcellent
reviewingteamthatwentoverthemanuscriptwithanamazing
eyefordetailandsavedmefrommanymoreembarrassing
errors.
ReviewersofthisandearliereditionsincludeChuckAllison
(ContributingEditor,C/C++UsersJournal),LanceAnderson
(SunMicrosystems),AlecBeaton(PointBase,Inc.),CliffBerg
(iSavvixCorporation),JoshuaBloch(SunMicrosystems),David
Brown,CorkyCartwright,FrankCohen(PushToTest),Chris

Crane(devXsolution),Dr.NicholasJ.DeLillo(Manhattan
College),RakeshDhoopar(Oracle),RobertEvans(SeniorStaff,
TheJohnsHopkinsUniversityAppliedPhysicsLab),DavidGeary
(Sabreware),BrianGoetz(PrincipalConsultant,QuiotixCorp.),
AngelaGordon(SunMicrosystems),DanGordon(Sun
Microsystems),RobGordon,JohnGray(UniversityofHartford),


CameronGregory(olabs.com),MartyHall(TheJohnsHopkins
UniversityAppliedPhysicsLab),VincentHardy(Sun
Microsystems),DanHarkey(SanJoseStateUniversity),William
Higgins(IBM),VladimirIvanovic(PointBase),JerryJackson
(ChannelPointSoftware),TimKimmet(PreviewSystems),Chris
Laffra,CharlieLai(SunMicrosystems),AngelikaLanger,Doug
Langston,HangLau(McGillUniversity),MarkLawrence,Doug
Lea(SUNYOswego),GregoryLongshore,BobLynch(Lynch
Associates),PhilipMilne(consultant),MarkMorrissey(The
OregonGraduateInstitute),MaheshNeelakanta(Florida
AtlanticUniversity),HaoPham,PaulPhilion,BlakeRagsdell,
YlberRamadani(RyersonUniversity),StuartReges(University
ofArizona),RichRosen(InteractiveDataCorporation),Peter
Sanders(ESSIUniversity,Nice,France),Dr.PaulSanghera(San
JoseStateUniversityandBrooksCollege),PaulSevinc(Teamup
AG),DevangShah(SunMicrosystems),RichardSlywczak
(NASA/GlennResearchCenter),BradleyA.Smith,Steven
Stelting(SunMicrosystems),ChristopherTaylor,LukeTaylor
(Valtech),GeorgeThiruvathukal,KimTopley(authorofCore
JFC),JanetTraub,PaulTyma(consultant),PetervanderLinden
(SunMicrosystems),andBurtWalsh.
CayHorstmannSanFrancisco,2008



Chapter1.StreamsandFiles
STREAMS
TEXTINPUTANDOUTPUT
READINGANDWRITINGBINARYDATA
ZIPARCHIVES
OBJECTSTREAMSANDSERIALIZATION
FILEMANAGEMENT
NEWI/O
REGULAREXPRESSIONS
Inthischapter,wecovertheJavaapplicationprogramming
interfaces(APIs)forinputandoutput.Youwilllearnhowto
accessfilesanddirectoriesandhowtoreadandwritedatain
binaryandtextformat.Thischapteralsoshowsyoutheobject
serializationmechanismthatletsyoustoreobjectsaseasilyas
youcanstoretextornumericdata.Next,weturntoseveral
improvementsthatweremadeinthe"newI/O"package
java.nio,introducedinJavaSE1.4.Wefinishthechapterwith
adiscussionofregularexpressions,eventhoughtheyarenot
actuallyrelatedtostreamsandfiles.Wecouldn'tfindabetter
placetohandlethattopic,andapparentlyneithercouldthe
Javateam—theregularexpressionAPIspecificationwas
attachedtothespecificationrequestforthe"newI/O"features
ofJavaSE1.4.

Streams
IntheJavaAPI,anobjectfromwhichwecanreadasequence
ofbytesiscalledaninputstream.Anobjecttowhichwecan



writeasequenceofbytesiscalledanoutputstream.These
sourcesanddestinationsofbytesequencescanbe—andoften
are—files,buttheycanalsobenetworkconnectionsandeven
blocksofmemory.TheabstractclassesInputStreamand
OutputStreamformthebasisforahierarchyofinput/output
(I/O)classes.
Becausebyte-orientedstreamsareinconvenientforprocessing
informationstoredinUnicode(recallthatUnicodeusesmultiple
bytespercharacter),thereisaseparatehierarchyofclassesfor
processingUnicodecharactersthatinheritfromtheabstract
ReaderandWriterclasses.Theseclasseshavereadandwrite
operationsthatarebasedontwo-byteUnicodecodeunits
ratherthanonsingle-bytecharacters.

ReadingandWritingBytes
TheInputStreamclasshasanabstractmethod:
abstractintread()
Thismethodreadsonebyteandreturnsthebytethatwasread,
or-1ifitencounterstheendoftheinputsource.Thedesigner
ofaconcreteinputstreamclassoverridesthismethodto
provideusefulfunctionality.Forexample,inthe
FileInputStreamclass,thismethodreadsonebytefromafile.
System.inisapredefinedobjectofasubclassofInputStream
thatallowsyoutoreadinformationfromthekeyboard.
TheInputStreamclassalsohasnonabstractmethodstoread
anarrayofbytesortoskipanumberofbytes.Thesemethods
calltheabstractreadmethod,sosubclassesneedtooverride
onlyonemethod.
Similarly,theOutputStreamclassdefinestheabstractmethod

abstractvoidwrite(intb)


whichwritesonebytetoanoutputlocation.
Boththereadandwritemethodsblockuntilthebytesare
actuallyreadorwritten.Thismeansthatifthestreamcannot
immediatelybeaccessed(usuallybecauseofabusynetwork
connection),thecurrentthreadblocks.Thisgivesotherthreads
thechancetodousefulworkwhilethemethodiswaitingforthe
streamtoagainbecomeavailable.
Theavailablemethodletsyoucheckthenumberofbytesthat
arecurrentlyavailableforreading.Thismeansafragmentlike
thefollowingisunlikelytoblock:
intbytesAvailable=in.available();
if(bytesAvailable>0)
{
byte[]data=newbyte[bytesAvailable];
in.read(data);
}

Whenyouhavefinishedreadingorwritingtoastream,closeit
bycallingtheclosemethod.Thiscallfreesupoperating
systemresourcesthatareinlimitedsupply.Ifanapplication
openstoomanystreamswithoutclosingthem,system
resourcescanbecomedepleted.Closinganoutputstreamalso
flushesthebufferusedfortheoutputstream:anycharacters
thatweretemporarilyplacedinabuffersothattheycouldbe
deliveredasalargerpacketaresentoff.Inparticular,ifyoudo
notcloseafile,thelastpacketofbytesmightneverbe
delivered.Youcanalsomanuallyflushtheoutputwiththe

flushmethod.
Evenifastreamclassprovidesconcretemethodstoworkwith
therawreadandwritefunctions,applicationprogrammers
rarelyusethem.Thedatathatyouareinterestedinprobably


containnumbers,strings,andobjects,notrawbytes.
Javagivesyoumanystreamclassesderivedfromthebasic
InputStreamandOutputStreamclassesthatletyouworkwith
dataintheformsthatyouusuallyuseratherthanatthebyte
level.


java.io.InputStream1.0
abstractintread()
readsabyteofdataandreturnsthebyte
read.Thereadmethodreturnsa-1atthe
endofthestream.
intread(byte[]b)
readsintoanarrayofbytesandreturnsthe
actualnumberofbytesread,or-1attheend
ofthestream.Thereadmethodreadsat
mostb.lengthbytes.
intread(byte[]b,intoff,intlen)
readsintoanarrayofbytes.Thereadmethod
returnstheactualnumberofbytesread,or-1
attheendofthestream.
Parameters: b

Thearrayintowhichthe

dataisread



off

Theoffsetintobwhere
thefirstbytesshouldbe
placed



len

Themaximumnumber
ofbytestoread

longskip(longn)
skipsnbytesintheinputstream.Returnsthe
actualnumberofbytesskipped(whichmay
belessthanniftheendofthestreamwas


encountered).
intavailable()
returnsthenumberofbytesavailablewithout
blocking.(Recallthatblockingmeansthatthe
currentthreadlosesitsturn.)
voidclose()
closestheinputstream.

voidmark(intreadlimit)
putsamarkeratthecurrentpositioninthe
inputstream.(Notallstreamssupportthis
feature.)Ifmorethanreadlimitbyteshave
beenreadfromtheinputstream,thenthe
streamisallowedtoforgetthemarker.
voidreset()
returnstothelastmarker.Subsequentcallsto
readrereadthebytes.Ifthereisnocurrent
marker,thenthestreamisnotreset.
booleanmarkSupported()
returnstrueifthestreamsupportsmarking.


×