I'll presume you've taken a Java course or studied an introductory book such as O'Reilly's Head First Java, Learning Java, or Java in a Nutshell.. Many of the longer examples in this boo
Trang 1tools and delivers expanded Mac OS
Trang 2coverage.
Trang 14Printed in the United States of America
Published by O'Reilly Media, Inc., 1005 Gravenstein HighwayNorth, Sebastopol, CA 95472
O'Reilly books may be purchased for educational, business, orsales promotional use Online editions are also available for
most titles (http://safari.oreilly.com) For more information,contact our corporate/institutional sales department: (800)
While every precaution has been taken in the preparation of thisbook, the publisher and authors assume no responsibility forerrors or omissions, or for damages resulting from the use ofthe information contained herein
Trang 15Preface to the Second EditionPreface to the First EditionWho This Book Is For
What's in This Book?
Platform Notes
Other Books
Conventions Used in This BookComments and Questions
Getting the Source Code
Acknowledgments
Trang 16JDK 1.5, code-named Tiger, is an exciting change to the Javalandscape It introduces several major new facilities, such asgeneric types for better data structuring, metadata for
annotating Java© classes in a flexible but well-defined manner,new pattern-based mechanisms for reading data, and a newmechanism for formatted printing In addition, a much largernumber of smaller but important changes add up to a new
release that is a must for Java developers It will be quite sometime before these mechanisms are fully understood and in widecirculation, but you will want to know about them right away
I wrote in the Afterword to the first edition that "writing thisbook has been a humbling experience." I should add that
maintaining it has been humbling, too While many reviewersand writers have been lavish with their praiseone very kind
reviewer called it "arguably the best book ever written on theJava programming language"I have been humbled by the
number of errors and omissions in the first edition In preparingthis edition, I have endeavored to correct these
At the same time I have added a number of new recipes andremoved a smaller number of old ones The largest single
addition is Chapter 8, which covers generic types and
enumerations, features that provide increased flexibility for
containers such as Java Collections Now that Java includes aregular expressions API, Chapter 4 has been converted from theApache Regular Expressions API to JDK 1.4 Regular
Expressions
I have somewhat hesitantly removed the chapter on NetworkWeb, including the JabaDot Web Portal Site program This wasthe longest single program example in the book, and it was
showing signs of needing considerable refactoring (in fact, itneeded a complete rewrite) In writing such a web site today,
Trang 17Linux and Windows
I wish to express my heartfelt thanks to all who sent in bothcomments and criticisms of the book after the first English
edition was in print Special mention must be made of one ofthe book's German translators,[1] Gisbert Selke, who read thefirst edition cover to cover during its translation and clarified myEnglish Gisbert did it all over again for the second edition andprovided many code refactorings, which have made this a farbetter book than it would be otherwise Going beyond the call ofduty, Gisbert even contributed one recipe (Recipe 26.4) andrevised some of the other recipes in the same chapter Thankyou, Gisbert! The second edition also benefited from comments
by Jim Burgess, who read large parts of the book Comments
on individual chapters were received from Jonathan Fuerth, Kim
Trang 18My thanks to the good guys behind the O'Reilly "bookquestions"list for fielding so many questions Thanks to Mike Loukides,Deb Cameron, and Marlowe Shaeffer for editorial and
production work on the second edition
Trang 20mangled C/C++ I wrote test and demo programs, sticking
them a few at a time into a directory that I called javasrc to
keep it separate from my C source (because often the programswould have the same name) And as I learned more about Java,
I began to see its advantages for many kinds of work, such asthe automatic memory reclaim and the elimination of pointer
calculations The javasrc directory kept growing I wrote a Java
course for Learning Tree,[2] and the directory grew faster,
reaching the point where it needed subdirectories Even then, itbecame increasingly difficult to find things, and it soon becameevident that some kind of documentation was needed
[2] One of the world's leading high-tech, vendor-independent training companies; see
http://www.learningtree.com/
In a sense, this book is the result of a high-speed collision
between my javasrc directory and a documentation framework established for another newcomer language In O'Reilly's Perl
Cookbook, Tom Christiansen and Nathan Torkington worked out
a very successful design, presenting the material in small,
focused articles called "recipes." The original model for such abook is, of course, the familiar kitchen cookbook Using the
term "cookbook" to refer to an enumeration of how-to recipesrelating to computers has a long history On the software side,
"learn more Java."
Trang 21copyright, just to discourage wholesale reproduction
Trang 22I'm going to assume that you know the basics of Java I won'ttell you how to println a string and a number at the same
time, or how to write a class that extends Applet and printsyour name in the window I'll presume you've taken a Java
course or studied an introductory book such as O'Reilly's Head
First Java, Learning Java, or Java in a Nutshell However,
Chapter 1 covers some techniques that you might not knowvery well and that are necessary to understand some of thelater material Feel free to skip around! Both the printed version
of the book and the electronic copy are heavily cross-referenced
Trang 23Unlike my Perl colleagues Tom and Nathan, I don't have to
spend as much time on the oddities and idioms of the language;Java is refreshingly free of strange quirks But that doesn't
mean it's trivial to learn well! If it were, there'd be no need forthis book My main approach, then, is to concentrate on theJava APIs I'll teach you by example what the APIs are and
what they are good for
Like Perl, Java is a language that grows on you and with you.And, I confess, I use Java most of the time nowadays ThingsI'd once done in C are nowexcept for device drivers and legacysystemsdone in Java
But Java is suited to a different range of tasks than Perl Perl(and other scripting languages, such as awk and Python) areparticularly suited to the "one-liner" utility task As Tom andNathan show, Perl excels at things like printing the 42nd linefrom a file While it can certainly do these things, Java, because
it is a compiled, object-oriented language, seems more suited
to "development in the large" or enterprise applications
development Indeed, much of the API material added in Java 2was aimed at this type of development However, I will
necessarily illustrate many techniques with shorter examplesand even code fragments Be assured that every line of codeyou see here has been compiled and run
Many of the longer examples in this book are tools that I
originally wrote to automate some mundane task or another.For example, MkIndex (described in Chapter 17) reads the top-level directory of the place where I keep all my Java example
source code and builds a browser-friendly index.html file for
that directory For another example, the body of the first editionwas partly composed in XML, a simplification that builds uponmany years of experience in SGML (the parent standard that led
Trang 24XmlForm program This program also handlesby use of anotherprogram, GetMarkfull and partial code insertions from the
source directory XmlForm is discussed in Chapter 21
Let's go over the organization of this book I start off Chapter 1,
by describing some methods of compiling your program on
different platforms, running them in different environments
(browser, command line, windowed desktop), and debugging.Chapter 2, moves from compiling and running your program togetting it to adapt to the surrounding countrysidethe other
programs that live in your computer
The next few chapters deal with basic APIs Chapter 3,
concentrates on one of the most basic but powerful data types
in Java, showing you how to assemble, dissect, compare, andrearrange what you might otherwise think of as ordinary text
Chapter 4, teaches you how to use the powerful regular
expressions technology from Unix in many string-matching andpattern-matching problem domains JDK 1.4 was the first
release to include this powerful technology; I also mention
several third-party regular expression packages
Chapter 5, deals both with built-in types such as int and
double, as well as the corresponding API classes (Integer,
Double, etc.) and the conversion and testing facilities they offer.There is also brief mention of the "big number" classes SinceJava programmers often need to deal in dates and times, bothlocally and internationally, Chapter 6, covers this important
topic
Trang 25languages, arrays in Java are linear, indexed collections of
similar-kind objects, as discussed in Chapter 7 This chaptergoes on to deal with the many "Collections" classes: powerfulways of storing quantities of objects in the java.util package
A new chapter was added in this section of the second edition.JDK 1.5 introduced a new dimension to the notion of data
structuring, by adapting the C++ notion of templates to theJava Collections; the result known as Generics is the main
subject of Chapter 8
Despite some syntactic resemblance to procedural languagessuch as C, Java is at heart an object-oriented programminglanguage Chapter 9, discusses some of the key notions of OOP
as it applies to Java, including the commonly overridden
methods of java.lang.Object and the important issue of
Design Patterns
The next few chapters deal with aspects of traditional input andoutput Chapter 10, details the rules for reading and writingfiles (Don't skip this if you think files are boring, as you'll needsome of this information in later chapters: you'll read and write
on serial or parallel ports in Chapter 12 and on a socket-basednetwork connection in Chapter 16!) Chapter 11, shows you
modified timeand about reading and modifying directories,
everything else about filessuch as finding their size and last-creating temporary files, and renaming files on disk Chapter
12, shows how you can use the javax.comm API to read/write
on serial and parallel ports using a standard Java API
Chapter 13, leads us into the GUI development side of things.This chapter is a mix of the lower-level details, such as drawinggraphics and setting fonts and colors, and very high-level
activities, such as controlling a video clip or movie In Chapter
14, I cover the higher-level aspects of a GUI, such as buttons,labels, menus, and the likethe GUI's predefined components.Once you have a GUI (really, before you actually write it), you'll
Trang 26do in Alberta, Arkansas, or Alabama
Since Java was originally promulgated as "the programminglanguage for the Internet," it's only fair that we spend some ofour time on networking in Java Chapter 16, covers the basics
of network programming from the client side, focusing on
sockets We'll then move to the server side in Chapter 17 InChapter 18, you'll learn more client-side techniques Programs
on the Net often need to generate electronic mail, so this
section ends with Chapter 19
Chapter 20, covers the essentials of the Java Database
Connectivity (JDBC) and Java Data Objects (JDO) packages,showing how you can connect to local or remote relational
databases, store and retrieve data, and find out informationabout query results or about the database
Another form of storing and exchanging data is XML Chapter
21, discusses XML's formats and some operations you can applyusing SAX and DOM, two standard Java APIs
Chapter 22, takes the distributed notion one step further anddiscusses Remote Method Invocation, Java's standard remoteprocedure call mechanism RMI lets you build clients, servers,and even "callback" scenarios, using a standard Java
mechanismthe Interfaceto describe the contract between clientand server
Chapter 23, shows how to create packages of classes that worktogether This chapter also talks about "deploying" or
distributing and installing your software
Chapter 24, tells you how to write classes that appear to domore than one thing at a time and let you take advantage ofpowerful multiprocessor hardware
Trang 27Sometimes you already have code written and working in
another language that can do part of your work for you, or youwant to use Java as part of a larger package Chapter 26,
shows you how to run an external program (compiled or script)and also interact directly with "native code" in C/C++ or otherlanguages
There isn't room in an 800-page book for everything I'd like totell you about Java The Chapter 27 presents some closing
thoughts and a link to my online summary of Java APIs thatevery Java developer should know about
No two programmers or writers will agree on the best order forpresenting all the Java topics To help you find your way
around, I've included extensive cross-references, mostly byrecipe number
Trang 28Java has gone through five major versions The first official
release was JDK 1.0, and its last bug-fixed version was 1.0.2.The second major release is Java JDK 1.1, and the latest bug-fixed version is 1.1.9, though it may be up from that by thetime you read this book The third major release, in December
1998, was to be known as JDK 1.2, but somebody at Sun
abruptly renamed JDK 1.2 at the time of its release to Java 2,and the implementation is known as Java 2 SDK 1.2 The
current version as of the writing of the first edition of this bookwas Java 2 SDK 1.3 (JDK 1.3), which was released in 2000
As the first edition of this book went to press, Java 2 Version1.4 was about to appear; it entered beta (which Sun calls "earlyaccess") around the time of the book's completion so I couldmention it only briefly The second edition of this book looks tohave better timing; Java 2 Version 1.5 is in beta as I am
updating the book
This book is aimed at the fifth version, Java 2 Standard Edition,Version 1.5 By the time of publication, I expect that all Javaprojects in development will be using JDK 1.4, with a very fewwedded to earlier versions for historical reasons I have usedseveral platforms to test this code for portability I've testedwith Sun's Linux JDK For the mass market, I've tested many ofthe programs on Sun's Win32 (Windows 2000/XP/2003)
implementation And, "for the rest of us," I've done most of myrecent development using Apple's Mac OS X Version 10.2.x andlater However, since Java is portable, I anticipate that the vastmajority of the examples will work on any Java-enabled
platform, except where extra APIs are required Not every
example has been tested on every platform, but all have beentested on at least oneand most on more than one
The Java API consists of two parts: core APIs and noncore APIs
Trang 29everything else But even this "core" is far from tiny: it weighs
in at around 50 packages and well over 2,000 public classes,averaging around 12 public methods each Programs that stick
to this core API are reasonably assured of portability to any
Java platform
The noncore APIs are further divided into standard extensionsand nonstandard extensions All standard extensions have
package names beginning with javax.[3] (and reference
implementations are available from Sun) A Java licensee (such
as Apple or IBM) is not required to implement every standardextension, but if it does, the interface of the standard extensionshould be adhered to This book calls your attention to any codethat depends on a standard extension Little code here depends
on nonstandard extensions, other than code listed in the bookitself My own package, com.darwinsys, contains some utilityclasses used here and there; you will see an import for this atthe top of any file that uses classes from it
[3] Note that not all packages named javax are extensions: javax.swing and its subpackagesthe Swing GUI packagesused to be extensions, but are now core.
In addition, two other platforms, the J2ME and the J2EE, are
standardized Java 2 Micro Edition is concerned with small
devices such as handhelds (PalmOS and others), cell phones,fax machines, and the like Within J2ME are various "profiles"for different classes of devices At the high end, the Java 2
Enterprise Edition (J2EE) is concerned with building large,
scalable, distributed applications Servlets, JavaServer Pages,JavaServer Faces, CORBA, RMI, JavaMail, Enterprise
JavaBeans© (EJBs), Transactions, and other APIs are part ofthe J2EE J2ME and J2EE packages normally begin with "javax"
as they are not core J2SE packages This book does not coverJ2ME at all but includes a few of the J2EE APIs that are alsouseful on the client side, such as RMI and JavaMail As
Trang 30edition of this book has been removed as there is now a Servlet
and JSP Cookbook.
Trang 31A lot of useful information is packed into this book However,due to the breadth of topics, it is not possible to give book-length treatment to any one topic Because of this, the bookalso contains references to many web sites and other books.This is in keeping with my target audience: the person whowants to learn more about Java
O'Reilly publishes, in my opinion, the best selection of Java
books on the market As the API continues to expand, so doesthe coverage You can find the latest versions and ordering
information on O'Reilly's Java books online at
http://java.oreilly.com, and you can buy them at most
bookstores, both physical and virtual You can also read themonline through a paid subscription service; see
http://safari.oreilly.com While many are mentioned at
appropriate spots in the book, a few deserve special mentionhere
Trang 32Harold, and Database Programming with JDBC and Java, by
George Reese, are also useful references
date list
General Programming Books
Donald E Knuth's The Art of Computer Programming has been
a source of inspiration to generations of computing studentssince its first publication by Addison Wesley in 1968 Volume 1
be used to solve real problemsare as relevant today as theywere years ago.[4]
[4] With apologies for algorithm decisions that are less relevant today given the massive changes
in computing power now available.
Though somewhat dated now, the book The Elements of
Trang 33(literally) for a generation of programmers with examples fromvarious structured programming languages Kernighan and
Plauger also wrote a pair of books, Software Tools and Software
Tools in Pascal, which demonstrated so much good advice on
programming that I used to advise all programmers to readthem However, these three books are dated now; many times Iwanted to write a follow-on book in a more modern language,
but instead defer to The Practice of Programming, Brian's
follow-onco-written with Rob Piketo the Software Tools series.
This book continues the Bell Labs (now part of Lucent) tradition
of excellence in software textbooks In Recipe 3.13, I have evenadapted one bit of code from their book
Refactoring, by Martin Fowler, covers a lot of " coding cleanups"
that can be applied to code to improve readability and
maintainability Just as the GOF book introduced new
Trang 34presented in a series of small, short, readable texts led by itsdesigner, Kent Beck A good overview of all the Agile methods is
Highsmith's Agile Software Development Ecosystems The first book in the XP series is Extreme Programming Explained.
Another group of important books on methodology, covering themore traditional object-oriented design, is the UML series led by
"the Three Amigos" (Booch, Jacobson, and Rumbaugh) Their
major works are the UML User Guide, UML Process, and others.
A smaller and more approachable book in the same series is
Martin Fowler's UML Distilled.
Trang 35This book uses the following conventions
Programming Conventions
I use the following terminology in this book A program means either an applet, a servlet, or an application An applet is for use in a browser A servlet is similar to an applet but for use in
a server An application is any other type of program A desktop application (a.k.a client) interacts with the user A server
program deals with a client indirectly, usually via a network
connection
The examples shown are in two varieties Those that begin withzero or more import statements, a Javadoc comment, and apublic class statement are complete examples Those that beginwith a declaration or executable statement, of course, are
excerpts However, the full versions of these excerpts have beencompiled and run, and the online source includes the full
versions
Recipes are numbered by chapter and number, so, for example,Recipe 7.5 refers to the fifth recipe in Chapter 7
Typesetting Conventions
The following typographic conventions are used in this book:
Italic
Trang 36Constant width
Used in code examples to show partial or complete Javasource code program listings It is also used for class
names, method names, variable names, and other
fragments of Java code
Constant width bold
Used for user input, such as commands that you type onthe command line
This icon signifies a tip, suggestion, or general note.
This icon indicates a warning or caution.
Many programs are accompanied by an example showing them
in action, run from the command line These will usually show aprompt ending in either $ for Unix or > for Windows, depending
on which computer I was using that day Text before this
prompt character can be ignored; it will be a pathname or ahostname, again depending on the system
Trang 37As mentioned earlier, I've tested all the code on at least one ofthe reference platforms, and most on several Still, there may
be platform dependencies, or even bugs, in my code or in someimportant Java implementation Please report any errors youfind, as well as your suggestions for future editions, by writingto:
bookquestions@oreilly.com
An O'Reilly web site for the book lists errata, examples, and anyadditional information You can access this page at:
http://www.oreilly.com/catalog/0596007019/
I also have a personal web site for the book:
http://javacook.darwinsys.com/
Both sites list errata and plans for future editions You'll alsofind the source code for all the Java code examples to
download; please don't waste your time typing them again! For
specific instructions, see the next section
Trang 38From my web site http://javacook.darwinsys.com, just followthe Downloads link You are presented with three choices:
1 Download the entire source archive as a single large zip file.
Download individual source files, indexed alphabetically aswell as by chapter
Download the binary JAR file for the com.darwinsys.*
package needed to compile many of the other programs
Most people will choose either option 1 or 2, but anyone whowants to compile my code will need option 3 See Recipe 1.5 forinformation on using these files
Downloading the entire source archive yields a large zip file withall the files from the book (and more) This archive can be
unpacked with jar (see Recipe 23.4), the free zip program from
Info-ZIP, the commercial WinZip or PKZIP, or any compatibletool The files are organized into subdirectories by topic, withone for strings (Chapter 3), regular expressions (Chapter 4),numbers (Chapter 5), and so on The archive also contains theindex by name and index by chapter files from the downloadsite, so you can easily find the files you need
Downloading individual files is easy, too: simply follow the linkseither by file/subdirectory name or by chapter Once you seethe file you want in your browser, use File Save or the
equivalent, or just copy and paste it from the browser into aneditor or IDE
The files are updated periodically, so if there are differencesbetween what's printed in the book and what you get, be glad,
Trang 39for you'll have received the benefit of hindsight.
Trang 40My life has been touched many times by the flow of the fatesbringing me into contact with the right person to show me theright thing at the right time Steve Munroe, with whom I've longsince lost touch, introduced me to computersin particular anIBM 360/30 at the Toronto Board of Education that was biggerthan a living room, had 32 or 64K of memory, and had perhapsthe power of a PC/XTin 1970 Herb Kugel took me under hiswing at the University of Toronto while I was learning about thelarger IBM mainframes that came later Terry Wood and DennisSmith at the University of Toronto introduced me to mini- andmicro-computers before there was an IBM PC On evenings andweekends, the Toronto Business Club of Toastmasters
International (http://www.toastmasters.org) and Al Lambert'sCanada SCUBA School allowed me to develop my public
speaking and instructional abilities Several people at the
University of Toronto, but especially Geoffrey Collyer, taught methe features and benefits of the Unix operating system at a timewhen I was ready to learn it
Greg Davidson of UCSD taught the first Learning Tree course Iattended and welcomed me as a Learning Tree instructor Yearslater, when the Oak language was about to be released on Sun'sweb site, Greg encouraged me to write to James Gosling andfind out about it James's reply of March 29th, 1995, that thelawyers had made them rename the language to Java and that
it was "just now" available for download, is the prized first entry
in my saved Java mailbox Mike Rozek took me on as a LearningTree course author for a Unix course and two Java courses
After Mike's departure from the company, Francesco Zamboni,Julane Marx, and Jennifer Urick in turn provided product
management of these courses Jennifer also arranged
permission for me to "reuse some code" in this book that hadpreviously been used in my Java course notes Finally, thanks to