1. 首页
  2. 编程语言
  3. Java
  4. Core Java Volume IIAdvanced Features

Core Java Volume IIAdvanced Features

上传者: 2020-05-25 19:15:12上传 PDF文件 51.26MB 热度 21次
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedastrademarks.Wherethosedesignations appearinthisbook,andthepublisherwasawareofatrademarkclaim,thedesignationshavebeenprintedwithinitialcapitallettersorinall itals OracleandJavaareregisteredtrademarksofOracleand/oritsaffiliates.Othernamesmaybetrademarksoftheirrespectiveowners Theauthorsandpublisherhavetakencareinthepreparationofthisbook,butmakenoexpressedorimpliedwarrantyofanykindandassumeno responsibilityforerrorsoromissions.Noliabilityisassumedforincidentalorconsequentialdamagesinconnectionwithorarisingoutoftheuse oftheinformationorprogramscontainedherein Thisdocumentisprovidedforinformationpurposesonlyandthecontentshereofaresubjecttochangewithoutnotice.Thisdocumentisnot warrantedtobeerror-free,norsubjecttoanyotherwarrantiesorconditions,whetherexpressedorallyorimpliedinlaw,includingimplied warrantiesandconditionsofmerchantabilityorfitnessforaparticularpurpose.Wespecificallydisclaimanyliabilitywithrespecttothisdocument andnocontractualobligationsareformedeitherdirectlyorindirectlybythisdocument.Thisdocumentmaynotbereproducedortransmittedinany formorbyanymeanselectronicormechanical,foranypurpose,withoutourpriorwrittenpermission Thepublisheroffersexcellentdiscountsonthisbookwhenorderedinquantityforbulkpurchasesorspecialsales,whichmayincludeelectronic versionsand/orcustomcoversandcontentparticulartoyourbusiness,traininggoals,marketingfocus,andbrandinginterests.Formore information,pleasecontact U.S.Coporateandgovernmentsales 800)382-3419 corpsales(@pearsontechqroup.com ForsalesoutsidetheUnitedStates,pleasecontact Internationalsales intemational@pearson.com VisitusontheWeb:informit.com/ph LibraryofCongressCataloging-in-PublicationData forstmann,CayS:1959 CoreJava/CaySHorstmann,GaryCornell-Ninthedition pagescm Includesindex ISBN978-0-13-708189-9(v1:pbk.alkpaper)1.Java(Computerprogram language)I.Cornell,Gary.I.Titi QA7673.J38H67532013 005133-dc23 2012035397 Copyright@2013Oracleand/oritsaffiliates.Allrightsreserved 500OracleParkwayRedwoodshores,ca94065 PrintedintheUnitedStatesofAmerica.Thispublicationisprotectedbycopyright,andpermissionmustbeobtainedfromthepublisherpriorto anyprohibitedreproduction,storageinaretrievalsystem,ortransmissioninanyformorbyanymeans,electronic,mechanical,photocopying recording,orlikewise.Toobtainpermissiontousematerialfromthiswork,pleasesubmitawrittenrequesttoPearsonEducation,Inc PermissionsDepartment,OneLakeStreet,UpperSaddleRiver,NewJersey07458,oryoumayfaxyourrequestto(201)236-3290 SBN13:9780-137081608 SBN-10:0-13-708160-X TextprintedintheUnitedStatesonrecycledpaperatEdwardsbrothersmalloyinAnnArbor,Michigan Firstprinting,February2013 Contents Preface Acknowledger nts Chapter1:StreamsandFiles 1.1Streams 1.1.1ReadingandWritingBytes 1.1.2TheCompleteStreamZoo 1.1.3CombiningStreamFilters 1.2TextInputandOutput 1.2.1HowtoWriteTextOutput 1.2.2HowtoReadTextInput 1.2.3SavingobjectsinTextFormat 1.24Charactersets 1.3ReadingandWritingBinarydata 1.3.1Random-AccessFiles 1.4ZPArchives 1.5ObiectStreamsandSerialization 1.5.1UnderstandingtheObjectSerializationFileFormat 1.5.2ModifyingtheDefaultSerializationMechanism 1.5.3SerializingsingletonsandTypesafeEnumerations 1.5.4Versioning 1.5.5UsingSerializationforCloning .6WorkingwithFiles 1.6.1Paths 1.6.2ReadingandWritingFiles 1.6.3CopyingMovingandDeletingFiles 1.6.4CreatingFilesandDirectories 1.6.5GettingFileInformation 1.6.6iteratingovertheFilesinaDirectory 1.6.7ZIPFileSystems 1.7Memory-MappedFiles 1.7.1TheBufferdatastructure 1.7.2FileLocking 1.8RegularExpressions Chapter2:XML 2.1introducing×ML 2.1.1Thestructureofanxmldocument 2.2ParsinganXMLDocument 2.3ValidatingXMLDocuments 2.3.1DocumentTypeDefinitions 2.32×MLSchel 2.3.3APracticalExample 2.4LocatingInformationwithXPath 2.5UsingNamespaces 2.6StreamingParsers 2.6.1UsingthesAXPal 2.6.2UsingtheStAXParser 2.7GeneratingXMLDocuments 2.7.1DocumentswithoutNamespaces 2.7.2DocumentswithNamespaces 2.7.3WritingDocume 2.7.4AnExample:GeneratinganSVGFile 2.7.5WritinganXMLDocumentwithStAX 2.8XSLTransformations Chapter3:Networking 3.1Connectingtoase 3.1.1SocketTimeouts 3.1.2IntemetAddresses 3.2mplementingServers 3.2.1ServingMultipleClients 3.2.2Half-Close 3.3InterruptibleSockets 3.4GettingWebData 3.4.1URLsandURis 3.4.2UsingaUR-ConnectiontoRetrieveInformation 3.4.3PostingFormData 3.5SendingE-Mail Chapter4:DatabaseProgramming 4.1TheDesignofJDBC 4.1.1JDBCDriverTypes 4.1.2TypicalUsesofJDBC 4.2TheStructuredQueryLanguage 4.3JDBCConfiguration 43.1Databaseurls 4.3.2DriverJARFiles 4.3.3StartingtheDatabase 4.3.4RegisteringtheDriverClass 4.3.5ConnectingtotheDatabase 4.4ExecutingSQLStatements 4.4.1ManagingConnections,Statements,andResultSets 4.4.2AnalyzingSQLExceptions 4.4.3Populatingadatab 4.5QueryExecution 4.5.1PreparedStatements 4.5.2ReadingandWritinglobs 4.5.3SQLEscapes 4.5.4MultipleResults 4.5.5RetrievingautogeneratedKeys 4.6ScrollableandUpdatableResultSets 4.6.1Scrollableresultsets 4.6.2UpdatableResultSets 4.7RowSets 4.7.1ConstructingRowSets 4.7.2CachedRowSets 4.8Metadata 4.9Transactions 4.9.1Savepoints 4.9.2BatchUpdates 4.9.3AdvancedSQLTypes 4.10ConnectionManagementinWebandEnterpriseApplications Chapter5:Internationalization 5.1Locales 5.2Numberformats 5.2.1Currencies 5.3Dateandtime 5.4Collation 5.4.1CollationStreng 5.4.2Decomposition 5.5MessageFormatting 5.5.1Choiceformats 5.6TextFilesandcharacterst 5.6.1CharacterEncodingofSourceFiles 5.7Resourcebundles 5.7.1LocatingResourceBundles 5.7.2PropertyFiles 5.7.3BundleClasses 5.8ACompleteExample Chapter6:AdvancedSwing 6.1Lists 6.1.1TheJL_stComponent 6.1.2Listmodels 6.1.3InsertingandRemovingvalues 6.1.4Renderingvalues 6.2Tables 6.2.1ASimpleTable 6.2.2Tablemodels 6.2.3WorkingwithRowsandColumns 6.2.3.1Columnclasses 6.2.3.2AccessingTableColumns 6.2.3.3ResizingColumns 6.2.3.4ResizingRows 6.2.3.5SelectingRows,Columns,andCells 6.2.3.6SortingRows 6.2.3.7FilteringRows 6.2.3.8HidingandDisplayingColumns 6.2.4CellRenderingandEditing 6.2.4.1RenderingtheHeader 6242ce‖Editing 6.24.3CustomEditors 6.3Trees 6.3.1SimpleTrees 6.3.1.1EditingTreesandTreePaths 6.3.2Nodeenumeration 6.3.3RenderingNodes 6.3.4ListeningtoTreeEvents 6.3.5CustomTreemodels 6.4TextComponents 6.4.1ChangeTrackinginTextComponents 6.4.2FormattedInputFields 6.4.2.1IntegerInput 6.4.2.2BehavioronLossofFocus 6.4.2.3Filters 6.4.Verifiers 6.4.2.5OtherStandardFormatters 6.4.2.6CustomFormatters 6.4.3TheSPinnerComponent 6.4.4DisplayingHTMLwiththeEditorpanc 6.5ProgressIndicators 6.5.1ProgressBars 6.5.2ProgressMonitors 6.5.3MonitoringtheProgressofInputStreams 6.6ComponentOrganizersandDecorators 6.6.1SplitPanes 6.6.2TabbedPanes 6.6.3DesktopPanesandInternalFrames 6.6.4cascadingandTiling 6.6.5VetoingPropertySettings 6.6.5.1DialogsinInternalFrames 6.6.5.2OutineDragging. 6.6.6.3Layers Chapter7:AdvancedAWT 7.1TheRenderingpipeline 7.2Shapes 7.2.1UsingtheShapeClasses 7.3Areas 7.4Strokes 7.5Paint 7.6CoordinateTransformations 7.7Clipping 7.8TransparencyandComposition 7.9RenderingHints 7.10ReadersandWritersforImages 7.10.1ObtainingReadersandWritersforImageFileTypes 7.10.2ReadingandWritingFileswithMultipleImages 7.11ImageManipulation 7.11.1ConstructingRasterImages 7.11.2FilteringImages 7.12Printing 7.12.1Graphicsprinti 7.12.2Multiple-PagePrinting 7.123PrintPreview 7.124Printservices 7.125StreamPrintservices 7.12.6PrintingAttributes 7.13TheClipboard 7.13.1ClassesandInterfacesfordatatransfer 7.13.2TransferringText 7.13.3TheTransferableInterfaceandDataFlavors 7.13.4BuildinganImageTransferable 7.13.5TransferringJavaObiectsviatheSystemClipboard 7.13.6UsingaLocalclipboardtoTransterObjectReferences 7.14DragandDrop 7.14.1DataTransferSupportinSwing 7.14.2DragSources 7.14.3DropTargets 7.15PlatformIntegration 7.15.1SplashScreens 7.15.2LaunchingDesktopApplications 7.15.3TheSystemTray Chapter8:JavaBeansComponents 8.1Whybeans? 8.2TheBean-WritingProces 8.3UsingBeanstoBuildanApplication 8.3.1PackagingBeansinJARFiles 8.3.2ComposingBeansinaBuilderenvironment 8.4NamingPatternsforBeanPropertiesandEvents 8.5BeanPropertyTypes 8.5.1SimpleProperties 8.5.2IndexedProperties 8.5.3BoundProperties 8.5.4ConstrainedProperties 8.6Beaninfoclasses 8.7PropertyEditors 8.7.1WritingPropertyEditors 8.7.1.1String-BasedPropertyEditors 8.7.1.2GU-BasedPropertyEditors 8.8Customizers 8.8.1WritingaCustomizerClass 8.9JavaBeanspersistence 8.9.1UsingJavaBeansPersistenceforArbitraryData 8.9.1.1WritingaPersistenceDelegatetoConstructanObject 8.9.1.2ConstructinganobiectfromProperties 8.9.1.3ConstructinganObjectwithaFactoryMethod 8.9.1.4PostconstructionWork 8.9.1.5TransientProperties 8.9.2ACompleteExampleforJavaBeansPersistence Chapter9:Security 9.1ClassLoaders 9.1.1TheClassLoaderHierarchy 9.1.2UsingClassLoadersasNamespaces 9.1.3WritingYourOwnClassLoader 9.2Bytecodeverification 9.3SecurityManagersandPermissions 9.3.1JavaPlatformSecurity 9.3.2SecurityPolicyFiles 9.3.3CustomPermissions 9.3.4ImplementationofaPermissionClass 9.4Userauthentication 9.4.1JAASLoginModules 9.5DigitalSignatures 9.5.1MessageDigests 9.5.2MessageSigning 9.5.3Verifyingasignature 9.5.4TheauthenticationProblem 9.5.5CertificateSigning 9.5.6CertificateRequests 9.6CodeSigning 9.6.1JARFilesignin 9.6.2SoftwareDeveloperCertificates 9.7Encryption 9.7.1SymmetricCipher 9.7.2KeyGeneration 9.7.3CipherStreams 9.7.4PublicKeyciphers Chapter10:Scripting,CompilingandAnnotationProcessing 10.1ScriptingfortheJavaPlatform 10.1.1GettingaScriptingEngine 10.1.2ScriptEvaluationandBindings 10.1.3RedirectingInputandOutput 10.1.4CallingScriptingFunctionsandMethods 10.1.5CompilingaScript 10.1.6AnExample:ScriptinggUIEvents 10.2TheCompilerAPI 10.2.1CompilingtheEasyway 10.2.2UsingCompilationTasks 10.2.3AnExample:DynamicJavaCodeGeneration 10.3UsingAnnotations 10.3.1AnExample:AnnotatingEventHandlers 10.4AnnotationSyntax 10.5StandardAnnotations 10.5.1AnnotationsforCompilation 10.5.2AnnotationsforManagingresources 10.5.3Meta-Annotations 10.6Source-LevelAnnotationProcessing 10.7BytecodeEngineering 10.7.1ModifyingBytecodesatLoadTime Chapter11:Distributedobiects 11.1Therolesofclientandserver 11.2Remotemethodcalls 11.2.1StubsandParameterMarshalling 11.3TheRMIProgrammingModel 11.3.1InterfacesandImplementations 11.3.2TheRMIRegistry 11.3.3DeployingtheProgram 11.3.4LoggingRMlactivity 114Parametersandreturnvaluesinremotemethods 11.4.1TransferringRemoteObjects 11.4.2TransferringNonremoteObjects 11.4.3DynamicClassLoading 11.4.4RemoteReferenceswithMultipleInterfaces 11.4.5RemoteObjectsandtheequals.nashCcde,andcloneMethods 11.5RemoteObiectActivation Chapter12:NativeMethods 12.1CallingaCFunctionfromaJavaProgram 12.2NumericParametersandreturnvalues 12.2.1UsingpritfforFormattingNumbers 12.3StringParameters 12.4AccessingFields 12.4.1AccessingInstanceFields 12.4.2AccessingStaticFields 12.5Encodingsignatures 12.6CallingJavaMethods 12.6.1InstanceMethods 12.6.2StaticMethods 12.6.3Constructors 12.6.4AlternativeMethodInvocations 12.7AccessingArrayElements 2.8HandlingErrors 12.9UsingtheInvocationAPI 12.10ACompleteExample:AccessingtheWindowsregistry 12.10.1OverviewoftheWindowsRegistry 12.10.2AJavaPlatformInterfaceforAccessingtheRegistry 12.10.3ImplementationofRegistryAccessFunctionsasNativeMethods Index Preface Tothereader ThebookyouhaveinyourhandsisthesecondvolumeofthenintheditionofCoreJava,fullyupdatedforJavaSE7.Thefirstvolumecoversthe essentialfeaturesofthelanguage;thisvolumedealswiththeadvancedtopicsthataprogrammerneedstoknowforprofessionalsoftware development.Thus,aswiththefirstvolumeandthepreviouseditionsofthisbook,wearestilltargetingprogrammerswhowanttoputJava technologytoworkonrealprojects Pleasenote:Ifyouareanexperienceddeveloperwhoiscomfortablewithadvancedlanguagefeaturessuchasinnerclassesandgenerics,you neednothavereadthefirstvolumeinordertobenefitfromthisvolumeWhilewedorefertosectionsofthepreviousvolumewhenappropriate (and,ofcourse,hopeyouwillbuyorhaveboughtVolumeD),youcanfindallthebackgroundmaterialyouneedinanycomprehensiveintroductory bookabouttheJavaplatform Finally,asisthecasewithanybook,errorsandinaccuraciesareinevitable.Shouldyoufindanyinthisbook,wewouldverymuchliketohear aboutthemOfcoursewewouldprefertohearaboutthemonlyonceForthisreasonwehaveputupawebsiteathttp:horstmanncom/coreiava withaFAQ,bugfixes,andworkarounds.Strategicallyplacedattheendofthebugreportwebpage(toencourageyoutoreadtheprevious reports)isaformthatyoucanusetoreportbugsorproblemsandtosendsuggestionsforimprovementstofutureeditions Aboutthisbook Thechaptersinthisbookare,forthemostpart,independentofeachother.Youshouldbeabletodelveintowhatevertopicinterestsyouthemost andreadthechaptersinanyorder Thetopicofchapter1isinputandoutputhandling(VO).InJava,alllOishandledthroughso-calledstreams.Streamsletyoudeal,inauniform manner,withcommunicationsamongvarioussourcesofdata,suchasfiles,networkconnections,ormemoryblocks.Weincludedetailed overageofthereaderandwriterclassesthatmakeiteasytodealwithUnicode.Weshowyouwhatgoesonunderthehoodwhenyouusethe objectserializationmechanism,whichmakessavingandloadingobjectseasyandconvenient.Wethenmoveontoregularexpressionsandthe NIO2libraryofJavaSE7,whichmakescommonoperations(suchasreadingalllinesinafile)veryconvenient. chapter2coversXML.WeshowyouhowtoparseXMLfiles,howtogenerateXML,andhowtouseXSLtransformations.Asausefulexample weshowyouhowtospecifythelayoutofaSwingforminXML.WealsodiscusstheXPathAPl,whichmakes"findingneedlesinXMLhaystacks mucheasier Chapter3coversthenetworkingAPl.Javamakesitphenomenallyeasytodocomplexnetworkprogramming.Weshowyouhowtomake networkconnectionstoservershowtoimplementyourownserversandhowtomakeHttpconnections Chapter4coversdatabaseprogramming.ThemainfocusisonJDBC,theJavadatabaseconnectivityaPithatletsJavaprogramsconnectto relationaldatabases.Weshowyouhowtowriteusefulprogramstohandlerealisticdatabasechores,usingacoresubsetoftheJDBCAPL.(A completetreatmentoftheJDBCAPIwouldrequireabookalmostaslongasthisone.Wefinishthechapterwithabriefintroductioninto hierarchicaldatabasesanddiscussJNDI(theJavaNamingandDirectoryInterface)andLdaP(theLightweightDirectoryAccessProtocol) Chapter5discussesafeaturethatwebelievecanonlygrowinimportance:internationalizationtheJavaprogramminglanguageisoneofthe fewlanguagesdesignedfromthestarttohandleUnicode,buttheinternationalizationsupportintheJavaplatformgoesmuchfurtherAsaresult, youcaninternationalizeJavaapplicationssothattheynotonlycrossplatformsbutcrosscountryboundariesaswell.Forexample,weshowyou howtowritearetirementcalculatorthatuseseitherenglish,German,orchineselanguages Chapter6containsalltheSwingmaterialthatdidn'tmakeitintoVolumel,especiallytheimportantbutcomplextreeandtablecomponents.We showthebasicusesofeditorpanes,thejavaimplementationofa"multipledocument"interfaceprogressindicatorsusedinmultithreaded programs,and"desktopintegrationfeatures"suchassplashscreensandsupportforthesystemtray.Again,wefocusonthemostuseful constructsthatyouarelikelytoencounterinpracticalprogrammingbecauseanencyclopediccoverageoftheentireSwinglibrarywouldfillseveral volumesandwouldonlybeofinteresttodedicatedtaxonomists Chapter7coverstheJava2DAPl,whichyoucanusetocreaterealisticdrawingsandspecialeffects.thechapteralsocoverssomeadvanced featuresoftheAWT(AbstractWindowingToolkitthatseemedtoospecializedforcoverageinVolumeIbutshould,nonetheless,bepartofevery programmer'stoolkitThesefeaturesincludeprintingandtheAPIsforcut-and-pasteanddrag-and-drop Chapter8explainswhatyouneedtoknowaboutthecomponentAPifortheJavaplatform--JavaBeans.Weshowyouhowtowriteyourown beansthatotherprogrammerscanmanipulateinintegratedbuilderenvironmentsWeconcludethischapterbyshowingyouhowyoucanuse JavaBeanspersistencetostoreyourdatainaformatthat-unlikeobjectserialization--issuitableforlong-termstorage Chapter9takesuptheJavasecuritymodel.TheJavaplatformwasdesignedfromthegrounduptobesecure,andthischaptertakesyouunder thehoodtoseehowthisdesignisimplemented.Weshowyouhowtowriteyourownclassloadersandsecuritymanagersforspecial-purpose applicationsThen,wetakeupthesecurityaPithatallowsforsuchimportantfeaturesasmessageandcodesigning,authorizationand authentication,andencryption.WeconcludewithexamplesthatusetheAESandRSaencryptionalgorithms Chapter10coversdistributedobjects.WecoverRMI(RemoteMethodInvocation)indetail.ThisaPIletsyouworkwithJavaobjectsthatare distributedovermultiplemachines Chapter11discussesthreetechniquesforprocessingcode.ThescriptingandcompileraPisallowyourprogramtocallcodeinscripting languagessuchasJavaScriptorGroovy,andtocompileJavacode.Annotationsallowyoutoaddarbitraryinformation(sometimescalled metadata)toaJavaprogram.Weshowyouhowannotationprocessorscanharvesttheseannotationsatthesourceorclassfilelevelandhow annotationscanbeusedtoinfluencethebehaviorofclassesatruntime.annotationsareonlyusefulwithtoolsandwehopethatourdiscussionwill helpyouselectusefulannotationprocessingtoolsforyourneeds Chapter12takesupnativemethods,whichletyoucallmethodswrittenforaspecificmachinesuchastheMicrosoftWindowsAPl.obviously,this featureiscontroversial:Usenativemethods,andthecross-platformnatureoftheJavaplatformvanishes.Nonetheless,everyseriousprogrammer writingJavaapplicationsforspecificplatformsneedstoknowthesetechniques.Attimes,youneedtoturntotheoperatingsystem'sAPiforyour targetplatformwhenyouinteractwithadeviceorservicethatisnotsupportedbyJava.Weillustratethisbyshowingyouhowtoaccessthe registryAPlinWindowsfromaJavaprogram Asalways,allchaptershavebeencompletelyrevisedforthelatestversionofJava.Outdatedmaterialhasbeenremoved,andthenewAPIsof Javase7arecoveredindetail Conventions
下载地址
用户评论