This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com < Day Day Up > • • • • • • Table of Contents Index Reviews Reader Reviews Errata Academic Java Cookbook, 2nd Edition By Ian F Darwin Publisher: O'Reilly Pub Date: June 2004 ISBN: 0-596-00701-9 Pages: 862 Java Cookbook, 2nd Edition gets you to the heart of what you need to know when you need to know it The completely revised and updated recipes in Java Cookbook, 2nd Edition cover all of the major APIs from Java 1.4 as well as the new 1.5 version It includes many specialized APIs like those for working with Struts, Ant, and other Open Source tools-and delivers expanded Mac OS coverage < Day Day Up > This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com < Day Day Up > • • • • • • Table of Contents Index Reviews Reader Reviews Errata Academic Java Cookbook, 2nd Edition By Ian F Darwin Publisher: O'Reilly Pub Date: June 2004 ISBN: 0-596-00701-9 Pages: 862 Copyright Preface Preface to the Second Edition Preface to the First Edition Who This Book Is For What's in This Book? Platform Notes Other Books Conventions Used in This Book Comments and Questions Getting the Source Code Acknowledgments Chapter Getting Started: Compiling, Running, and Debugging Introduction Section 1.1 Compiling and Running Java: JDK Section 1.2 Editing and Compiling with a Color-Highlighting Editor Section 1.3 Compiling, Running, and Testing with an IDE Section 1.4 Using CLASSPATH Effectively Section 1.5 Using the com.darwinsys API Classes from This Book Section 1.6 Compiling the Source Code Examples from This Book Section 1.7 Automating Compilation with Ant Section 1.8 Running Applets Section 1.9 Dealing with Deprecation Warnings Section 1.10 Conditional Debugging Without #ifdef Section 1.11 Debugging Printouts Section 1.12 Maintaining Program Correctness with Assertions Section 1.13 Debugging with JDB This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 1.14 Unit Testing: Avoid the Need for Debuggers Section 1.15 Getting Readable Tracebacks Section 1.16 Finding More Java Source Code Section 1.17 Program: Debug Chapter Interacting with the Environment Introduction Section 2.1 Getting Environment Variables Section 2.2 System Properties Section 2.3 Writing JDK Release-Dependent Code Section 2.4 Writing Operating System-Dependent Code Section 2.5 Using Extensions or Other Packaged APIs Section 2.6 Parsing Command-Line Arguments Chapter Strings and Things Introduction Section 3.1 Taking Strings Apart with Substrings Section 3.2 Taking Strings Apart with StringTokenizer Section 3.3 Putting Strings Together with +, StringBuilder (JDK 1.5), and StringBuffer Section 3.4 Processing a String One Character at a Time Section 3.5 Aligning Strings Section 3.6 Converting Between Unicode Characters and Strings Section 3.7 Reversing a String by Word or by Character Section 3.8 Expanding and Compressing Tabs Section 3.9 Controlling Case Section 3.10 Indenting Text Documents Section 3.11 Entering Nonprintable Characters Section 3.12 Trimming Blanks from the End of a String Section 3.13 Parsing Comma-Separated Data Section 3.14 Program: A Simple Text Formatter Section 3.15 Program: Soundex Name Comparisons Chapter Pattern Matching with Regular Expressions Introduction Section 4.1 Regular Expression Syntax Section 4.2 Using regexes in Java: Test for a Pattern Section 4.3 Finding the Matching Text Section 4.4 Replacing the Matched Text Section 4.5 Printing All Occurrences of a Pattern Section 4.6 Printing Lines Containing a Pattern Section 4.7 Controlling Case in Regular Expressions Section 4.8 Matching "Accented" or Composite Characters Section 4.9 Matching Newlines in Text Section 4.10 Program: Apache Logfile Parsing Section 4.11 Program: Data Mining Section 4.12 Program: Full Grep Chapter Numbers Introduction Section 5.1 Checking Whether a String Is a Valid Number Section 5.2 Storing a Larger Number in a Smaller Number Section 5.3 Converting Numbers to Objects and Vice Versa Section 5.4 Taking a Fraction of an Integer Without Using Floating Point Section 5.5 Ensuring the Accuracy of Floating-Point Numbers Section 5.6 Comparing Floating-Point Numbers Section 5.7 Rounding Floating-Point Numbers Section 5.8 Formatting Numbers This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 5.8 Formatting Numbers Section 5.9 Converting Between Binary, Octal, Decimal, and Hexadecimal Section 5.10 Operating on a Series of Integers Section 5.11 Working with Roman Numerals Section 5.12 Formatting with Correct Plurals Section 5.13 Generating Random Numbers Section 5.14 Generating Better Random Numbers Section 5.15 Calculating Trigonometric Functions Section 5.16 Taking Logarithms Section 5.17 Multiplying Matrices Section 5.18 Using Complex Numbers Section 5.19 Handling Very Large Numbers Section 5.20 Program: TempConverter Section 5.21 Program: Number Palindromes Chapter Dates and Times Introduction Section 6.1 Finding Today's Date Section 6.2 Printing Date/Time in a Given Format Section 6.3 Representing Dates in Other Epochs Section 6.4 Converting YMDHMS to a Calendar or Epoch Seconds Section 6.5 Parsing Strings into Dates Section 6.6 Converting Epoch Seconds to DMYHMS Section 6.7 Adding to or Subtracting from a Dateor Calendar Section 6.8 Difference Between Two Dates Section 6.9 Comparing Dates Section 6.10 Day of Week/Month/Year or Week Number Section 6.11 Creating a Calendar Page Section 6.12 Measuring Elapsed Time Section 6.13 Sleeping for a While Section 6.14 Program: Reminder Service Chapter Structuring Data with Java Introduction Section 7.1 Using Arrays for Data Structuring Section 7.2 Resizing an Array Section 7.3 Like an Array, but More Dynamic Section 7.4 Using Iterators for Data-Independent Access Section 7.5 Structuring Data in a Linked List Section 7.6 Mapping with Hashtable and HashMap Section 7.7 Storing Strings in Properties and Preferences Section 7.8 Sorting a Collection Section 7.9 Avoiding the Urge to Sort Section 7.10 Eschewing Duplication Section 7.11 Finding an Object in a Collection Section 7.12 Converting a Collection to an Array Section 7.13 Rolling Your Own Iterator Section 7.14 Stack Section 7.15 Multidimensional Structures Section 7.16 Finally, Collections Section 7.17 Program: Timing Comparisons Chapter Data Structuring with Generics, foreach, and Enumerations (JDK 1.5) Introduction Section 8.1 Using Generic Collections Section 8.2 Using "foreach" Loops This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 8.3 Avoid Casting by Using Generics Section 8.4 Let Java Convert with AutoBoxing and AutoUnboxing Section 8.5 Using Typesafe Enumerations Section 8.6 Program: MediaInvoicer Chapter Object-Oriented Techniques Introduction Section 9.1 Printing Objects: Formatting with toString( ) Section 9.2 Overriding the Equals Method Section 9.3 Overriding the hashCode Method Section 9.4 The Clone Method Section 9.5 The Finalize Method Section 9.6 Using Inner Classes Section 9.7 Providing Callbacks via Interfaces Section 9.8 Polymorphism/Abstract Methods Section 9.9 Passing Values Section 9.10 Enforcing the Singleton Pattern Section 9.11 Roll Your Own Exceptions Section 9.12 Program: Plotter Chapter 10 Input and Output Introduction Section 10.1 Reading Standard Input Section 10.2 Writing Standard Output Section 10.3 Printing with the 1.5 Formatter Section 10.4 Scanning a File with StreamTokenizer Section 10.5 Scanning Input with the 1.5 Scanner Class Section 10.6 Opening a File by Name Section 10.7 Copying a File Section 10.8 Reading a File into a String Section 10.9 Reassigning the Standard Streams Section 10.10 Duplicating a Stream as It Is Written Section 10.11 Reading/Writing a Different Character Set Section 10.12 Those Pesky End-of-Line Characters Section 10.13 Beware Platform-Dependent File Code Section 10.14 Reading "Continued" Lines Section 10.15 Binary Data Section 10.16 Seeking Section 10.17 Writing Data Streams from C Section 10.18 Saving and Restoring Java Objects Section 10.19 Preventing ClassCastExceptions with SerialVersionUID Section 10.20 Reading and Writing JAR or Zip Archives Section 10.21 Reading and Writing Compressed Files Section 10.22 Program: Text to PostScript Chapter 11 Directory and Filesystem Operations Introduction Section 11.1 Getting File Information Section 11.2 Creating a File Section 11.3 Renaming a File Section 11.4 Deleting a File Section 11.5 Creating a Transient File Section 11.6 Changing File Attributes Section 11.7 Listing a Directory Section 11.8 Getting the Directory Roots Section 11.9 Creating New Directories This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 11.9 Creating New Directories Section 11.10 Program: Find Chapter 12 Programming External Devices: Serial and Parallel Ports Introduction Section 12.1 Choosing a Port Section 12.2 Opening a Serial Port Section 12.3 Opening a Parallel Port Section 12.4 Resolving Port Conflicts Section 12.5 Reading and Writing: Lock-Step Section 12.6 Reading and Writing: Event-Driven Section 12.7 Reading and Writing: Threads Section 12.8 Program: Penman Plotter Chapter 13 Graphics and Sound Introduction Section 13.1 Painting with a Graphics Object Section 13.2 Testing Graphical Components Section 13.3 Drawing Text Section 13.4 Drawing Centered Text in a Component Section 13.5 Drawing a Drop Shadow Section 13.6 Drawing Text with 2D Section 13.7 Drawing Text with an Application Font Section 13.8 Drawing an Image Section 13.9 Playing a Sound File Section 13.10 Playing a Video Clip Section 13.11 Printing in Java Section 13.12 Program: PlotterAWT Section 13.13 Program: Grapher Chapter 14 Graphical User Interfaces Introduction Section 14.1 Displaying GUI Components Section 14.2 Designing a Window Layout Section 14.3 A Tabbed View of Life Section 14.4 Action Handling: Making Buttons Work Section 14.5 Action Handling Using Anonymous Inner Classes Section 14.6 Terminating a Program with"Window Close" Section 14.7 Dialogs: When Later Just Won't Do Section 14.8 Catching and Formatting GUI Exceptions Section 14.9 Getting Program Output into a Window Section 14.10 Choosing a Value with JSpinner Section 14.11 Choosing a File with JFileChooser Section 14.12 Choosing a Color Section 14.13 Formatting JComponents with HTML Section 14.14 Centering a Main Window Section 14.15 Changing a Swing Program's Look and Feel Section 14.16 Enhancing Your GUI for Mac OS X Section 14.17 Program: Custom Font Chooser Section 14.18 Program: Custom Layout Manager Chapter 15 Internationalization and Localization Introduction Section 15.1 Creating a Button with I18N Resources Section 15.2 Listing Available Locales Section 15.3 Creating a Menu with I18N Resources Section 15.4 Writing Internationalization Convenience Routines This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 15.5 Creating a Dialog with I18N Resources Section 15.6 Creating a Resource Bundle Section 15.7 Extracting Strings from Your Code Section 15.8 Using a Particular Locale Section 15.9 Setting the Default Locale Section 15.10 Formatting Messages Section 15.11 Program: MenuIntl Section 15.12 Program: BusCard Chapter 16 Network Clients Introduction Section 16.1 Contacting a Server Section 16.2 Finding and Reporting Network Addresses Section 16.3 Handling Network Errors Section 16.4 Reading and Writing Textual Data Section 16.5 Reading and Writing Binary Data Section 16.6 Reading and Writing Serialized Data Section 16.7 UDP Datagrams Section 16.8 Program: TFTP UDP Client Section 16.9 Program: Telnet Client Section 16.10 Program: Chat Client Chapter 17 Server-Side Java: Sockets Introduction Section 17.1 Opening a Server for Business Section 17.2 Returning a Response (String or Binary) Section 17.3 Returning Object Information Section 17.4 Handling Multiple Clients Section 17.5 Serving the HTTP Protocol Section 17.6 Securing a Web Server with SSL and JSSE Section 17.7 Network Logging Section 17.8 Network Logging with log4j Section 17.9 Network Logging with JDK 1.4 Section 17.10 Finding Network Interfaces Section 17.11 Program: A Java Chat Server Chapter 18 Network Clients II: Applets and Web Clients Introduction Section 18.1 Embedding Java in a Web Page Section 18.2 Applet Techniques Section 18.3 Contacting a Server on the Applet Host Section 18.4 Making an Applet Show a Document Section 18.5 Making an Applet Run JavaScript Section 18.6 Making an Applet Run a CGI Script Section 18.7 Reading the Contents of a URL Section 18.8 URI, URL, or URN? Section 18.9 Extracting HTML from a URL Section 18.10 Extracting URLs from a File Section 18.11 Converting a Filename to a URL Section 18.12 Program: MkIndex Section 18.13 Program: LinkChecker Chapter 19 Java and Electronic Mail Introduction Section 19.1 Sending Email: Browser Version Section 19.2 Sending Email: For Real Section 19.3 Mail-Enabling a Server Program This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 19.3 Mail-Enabling a Server Program Section 19.4 Sending MIME Mail Section 19.5 Providing Mail Settings Section 19.6 Sending Mail Without Using JavaMail Section 19.7 Reading Email Section 19.8 Program: MailReaderBean Section 19.9 Program: MailClient Chapter 20 Database Access Introduction Section 20.1 Easy Database Access with JDO Section 20.2 Text-File Databases Section 20.3 DBM Databases Section 20.4 JDBC Setup and Connection Section 20.5 Connecting to a JDBC Database Section 20.6 Sending a JDBC Query and Getting Results Section 20.7 Using JDBC Prepared Statements Section 20.8 Using Stored Procedures with JDBC Section 20.9 Changing Data Using a ResultSet Section 20.10 Storing Results in a RowSet Section 20.11 Changing Data Using SQL Section 20.12 Finding JDBC Metadata Section 20.13 Program: SQLRunner Chapter 21 XML Introduction Section 21.1 Generating XML from Objects Section 21.2 Transforming XML with XSLT Section 21.3 Parsing XML with SAX Section 21.4 Parsing XML with DOM Section 21.5 Verifying Structure with a DTD Section 21.6 Generating Your Own XML with DOM Section 21.7 Program: xml2mif Chapter 22 Distributed Java: RMI Introduction Section 22.1 Defining the RMI Contract Section 22.2 Creating an RMI Client Section 22.3 Creating an RMI Server Section 22.4 Deploying RMI Across a Network Section 22.5 Program: RMI Callbacks Section 22.6 Program: NetWatch Chapter 23 Packages and Packaging Introduction Section 23.1 Creating a Package Section 23.2 Documenting Classes with Javadoc Section 23.3 Beyond JavaDoc: Annotations/Metadata (JDK 1.5) and XDoclet Section 23.4 Archiving with jar Section 23.5 Running an Applet from a JAR Section 23.6 Running an Applet with a Modern JDK Section 23.7 Running a Main Program from a JAR Section 23.8 Preparing a Class as a JavaBean Section 23.9 Pickling Your Bean into a JAR Section 23.10 Packaging a Servlet into a WAR File Section 23.11 "Write Once, Install Anywhere" Section 23.12 "Write Once, Install on Mac OS X" This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 23.13 Java Web Start Section 23.14 Signing Your JAR File Chapter 24 Threaded Java Introduction Section 24.1 Running Code in a Different Thread Section 24.2 Displaying a Moving Image with Animation Section 24.3 Stopping a Thread Section 24.4 Rendezvous and Timeouts Section 24.5 Synchronizing Threads with the synchronized Keyword Section 24.6 Simplifying Synchronization with 1.5 Locks Section 24.7 Synchronizing Threads with wait( ) and notifyAll( ) Section 24.8 Simplifying Producer-Consumer with the 1.5 Queue Interface Section 24.9 Background Saving in an Editor Section 24.10 Program: Threaded Network Server Section 24.11 Simplifying Servers Using the Concurrency Utilities (JDK 1.5) Chapter 25 Introspection, or "A Class Named Class" Introduction Section 25.1 Getting a Class Descriptor Section 25.2 Finding and Using Methods and Fields Section 25.3 Loading and Instantiating a Class Dynamically Section 25.4 Constructing a Class from Scratch Section 25.5 Performance Timing Section 25.6 Printing Class Information Section 25.7 Program: CrossRef Section 25.8 Program: AppletViewer Chapter 26 Using Java with Other Languages Introduction Section 26.1 Running a Program Section 26.2 Running a Program and Capturing Its Output Section 26.3 Mixing Java and Scripts with BSF Section 26.4 Marrying Java and Perl Section 26.5 Blending in Native Code (C/C++) Section 26.6 Calling Java from Native Code Section 26.7 Program: DBM Afterword Colophon Index < Day Day Up > This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com < Day Day Up > Copyright © 2004, 2001 O'Reilly Media, Inc Printed in the United States of America Published by O'Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472 O'Reilly books may be purchased for educational, business, or sales promotional use Online editions are also available for most titles (http://safari.oreilly.com) For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks of O'Reilly Media, Inc The Cookbook series designations, Java Cookbook, the image of a domestic chicken, and related trade dress are trademarks of O'Reilly Media, Inc Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries O'Reilly Media, Inc is independent of Sun Microsystems, Inc Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and O'Reilly Media, Inc was aware of a trademark claim, the designations have been printed in caps or initial caps While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein < Day Day Up > This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com < Day Day Up > Other Books A 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 book also contains references to many web sites and other books This is in keeping with my target audience: the person who wants 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 does the 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 them online through a paid subscription service; see http://safari.oreilly.com While many are mentioned at appropriate spots in the book, a few deserve special mention here First and foremost, David Flanagan's Java in a Nutshell offers a brief overview of the language and API and a detailed reference to the most essential packages This is handy to keep beside your computer Head First Java offers a much more whimsical introduction to the language and is recommended for the less experienced developer A definitive (and monumental) description of programming the Swing GUI is Java Swing by Marc Loy, Robert Eckstein, Dave Wood, James Elliott, and Brian Cole Java Virtual Machine, by Jon Meyer and Troy Downing, will intrigue the person who wants to know more about what's under the hood This book is out of print but can be found used and in libraries Java Network Programming and Java I/O, both by Elliotte Rusty Harold, and Database Programming with JDBC and Java, by George Reese, are also useful references There are many more; see the O'Reilly web site for an up-to-date list Other Java Books You should not consider releasing a GUI application unless you have read Sun's official Java Look and Feel Design Guidelines (Addison Wesley) This work presents the views of a large group of human factors and user-interface experts at Sun who have worked with the Swing GUI package since its inception; they tell you how to make it work well General Programming Books Donald E Knuth's The Art of Computer Programming has been a source of inspiration to generations of computing students since its first publication by Addison Wesley in 1968 Volume covers Fundamental Algorithms, Volume is Seminumerical Algorithms, and Volume is Sorting and Searching The remaining four volumes in the projected series are still not completed Although his examples are far from Java (he invented a hypothetical assembly language for his examples), many of his discussions of algorithms—of how computers ought to be used to solve real problems—are as relevant today as they were 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 Programming Style, by Kernighan and Plauger, set the style (literally) for a generation of programmers with examples from various 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 read them However, these three books are dated now; many times I wanted to write a follow-on book in a more modern language, but instead defer to The Practice of Programming, Brian's follow-on—co-written with Rob Pike—to 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 even adapted one bit of code from their book See also The Pragmatic Programmer by Andrew Hunt and David Thomas (Addison Wesley) Design Books Peter Coad's Java Design (PTR-PH/Yourdon Press) discusses the issues of object-oriented analysis and design specifically for Java Coad is somewhat critical of Java's implementation of the observable-observer paradigm and offers his own replacement for it One of the most famous books on object-oriented design in recent years is Design Patterns, by Gamma, Helm, Johnson, and Vlissides (Addison Wesley) These authors are often collectively called "the gang of four," resulting in their book sometimes being referred to as "the GOF book." One of my colleagues called it "the best book on object-oriented design ever," and I agree; at the very least it's among the best This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com ever," and I agree; at the very least it's among the best 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 terminology that helps developers and others communicate about how code is to be designed, Fowler's book provided a vocabulary for discussing how it is to be improved Many of the "refactorings" now appear in the Refactoring Menu of the Eclipse IDE (see Recipe 1.3) Two important streams of methodology theories are currently in circulation The first is collectively known as Agile Methods, and its best-known member is Extreme Programming XP (the methodology, not last year's flavor of Microsoft's OS) is presented in a series of small, short, readable texts led by its designer, 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 the more 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 < Day Day Up > This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com < Day Day Up > Conventions Used in This Book This 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 with zero or more import statements, a Javadoc comment, and a public class statement are complete examples Those that begin with a declaration or executable statement, of course, are excerpts However, the full versions of these excerpts have been compiled 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 Typesetting Conventions The following typographic conventions are used in this book: Italic Used for commands, filenames, and example URLs It is also used to define new terms when they first appear in the text Constant width Used in code examples to show partial or complete Java source 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 on the 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 a prompt 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 a hostname, again depending on the system < Day Day Up > This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com < Day Day Up > Comments and Questions As mentioned earlier, I've tested all the code on at least one of the reference platforms, and most on several Still, there may be platform dependencies, or even bugs, in my code or in some important Java implementation Please report any errors you find, as well as your suggestions for future editions, by writing to: O'Reilly Media, Inc 1005 Gravenstein Highway North Sebastopol, CA 95472 (800) 998-9938 (in the United States or Canada) (707) 829-0515 (international or local) (707) 829-0104 (fax) To ask technical questions or comment on the book, send email to: bookquestions@oreilly.com An O'Reilly web site for the book lists errata, examples, and any additional 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 also find 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 < Day Day Up > This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com < Day Day Up > Getting the Source Code From my web site http://javacook.darwinsys.com, just follow the Downloads link You are presented with three choices: Download the entire source archive as a single large zip file Download individual source files, indexed alphabetically as well 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 or 2, but anyone who wants to compile my code will need option See Recipe 1.5 for information on using these files Downloading the entire source archive yields a large zip file with all 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 compatible tool The files are organized into subdirectories by topic, with one for strings (Chapter 3), regular expressions (Chapter 4), numbers (Chapter 5), and so on The archive also contains the index by name and index by chapter files from the download site, so you can easily find the files you need Downloading individual files is easy, too: simply follow the links either by file/subdirectory name or by chapter Once you see the file you want in your browser, use File Save or the equivalent, or just copy and paste it from the browser into an editor or IDE The files are updated periodically, so if there are differences between what's printed in the book and what you get, be glad, for you'll have received the benefit of hindsight < Day Day Up > This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com < Day Day Up > Preface Preface to the Second Edition Preface to the First Edition Who This Book Is For What's in This Book? Platform Notes Other Books Conventions Used in This Book Comments and Questions Getting the Source Code Acknowledgments < Day Day Up > This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com < Day Day Up > • • • • • • Table of Contents Index Reviews Reader Reviews Errata Academic Java Cookbook, 2nd Edition By Ian F Darwin Publisher: O'Reilly Pub Date: June 2004 ISBN: 0-596-00701-9 Pages: 862 Java Cookbook, 2nd Edition gets you to the heart of what you need to know when you need to know it The completely revised and updated recipes in Java Cookbook, 2nd Edition cover all of the major APIs from Java 1.4 as well as the new 1.5 version It includes many specialized APIs like those for working with Struts, Ant, and other Open Source tools-and delivers expanded Mac OS coverage < Day Day Up > This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com < Day Day Up > • • • • • • Table of Contents Index Reviews Reader Reviews Errata Academic Java Cookbook, 2nd Edition By Ian F Darwin Publisher: O'Reilly Pub Date: June 2004 ISBN: 0-596-00701-9 Pages: 862 Copyright Preface Preface to the Second Edition Preface to the First Edition Who This Book Is For What's in This Book? Platform Notes Other Books Conventions Used in This Book Comments and Questions Getting the Source Code Acknowledgments Chapter Getting Started: Compiling, Running, and Debugging Introduction Section 1.1 Compiling and Running Java: JDK Section 1.2 Editing and Compiling with a Color-Highlighting Editor Section 1.3 Compiling, Running, and Testing with an IDE Section 1.4 Using CLASSPATH Effectively Section 1.5 Using the com.darwinsys API Classes from This Book Section 1.6 Compiling the Source Code Examples from This Book Section 1.7 Automating Compilation with Ant Section 1.8 Running Applets Section 1.9 Dealing with Deprecation Warnings Section 1.10 Conditional Debugging Without #ifdef Section 1.11 Debugging Printouts Section 1.12 Maintaining Program Correctness with Assertions Section 1.13 Debugging with JDB This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 1.14 Unit Testing: Avoid the Need for Debuggers Section 1.15 Getting Readable Tracebacks Section 1.16 Finding More Java Source Code Section 1.17 Program: Debug Chapter Interacting with the Environment Introduction Section 2.1 Getting Environment Variables Section 2.2 System Properties Section 2.3 Writing JDK Release-Dependent Code Section 2.4 Writing Operating System-Dependent Code Section 2.5 Using Extensions or Other Packaged APIs Section 2.6 Parsing Command-Line Arguments Chapter Strings and Things Introduction Section 3.1 Taking Strings Apart with Substrings Section 3.2 Taking Strings Apart with StringTokenizer Section 3.3 Putting Strings Together with +, StringBuilder (JDK 1.5), and StringBuffer Section 3.4 Processing a String One Character at a Time Section 3.5 Aligning Strings Section 3.6 Converting Between Unicode Characters and Strings Section 3.7 Reversing a String by Word or by Character Section 3.8 Expanding and Compressing Tabs Section 3.9 Controlling Case Section 3.10 Indenting Text Documents Section 3.11 Entering Nonprintable Characters Section 3.12 Trimming Blanks from the End of a String Section 3.13 Parsing Comma-Separated Data Section 3.14 Program: A Simple Text Formatter Section 3.15 Program: Soundex Name Comparisons Chapter Pattern Matching with Regular Expressions Introduction Section 4.1 Regular Expression Syntax Section 4.2 Using regexes in Java: Test for a Pattern Section 4.3 Finding the Matching Text Section 4.4 Replacing the Matched Text Section 4.5 Printing All Occurrences of a Pattern Section 4.6 Printing Lines Containing a Pattern Section 4.7 Controlling Case in Regular Expressions Section 4.8 Matching "Accented" or Composite Characters Section 4.9 Matching Newlines in Text Section 4.10 Program: Apache Logfile Parsing Section 4.11 Program: Data Mining Section 4.12 Program: Full Grep Chapter Numbers Introduction Section 5.1 Checking Whether a String Is a Valid Number Section 5.2 Storing a Larger Number in a Smaller Number Section 5.3 Converting Numbers to Objects and Vice Versa Section 5.4 Taking a Fraction of an Integer Without Using Floating Point Section 5.5 Ensuring the Accuracy of Floating-Point Numbers Section 5.6 Comparing Floating-Point Numbers Section 5.7 Rounding Floating-Point Numbers Section 5.8 Formatting Numbers This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 5.8 Formatting Numbers Section 5.9 Converting Between Binary, Octal, Decimal, and Hexadecimal Section 5.10 Operating on a Series of Integers Section 5.11 Working with Roman Numerals Section 5.12 Formatting with Correct Plurals Section 5.13 Generating Random Numbers Section 5.14 Generating Better Random Numbers Section 5.15 Calculating Trigonometric Functions Section 5.16 Taking Logarithms Section 5.17 Multiplying Matrices Section 5.18 Using Complex Numbers Section 5.19 Handling Very Large Numbers Section 5.20 Program: TempConverter Section 5.21 Program: Number Palindromes Chapter Dates and Times Introduction Section 6.1 Finding Today's Date Section 6.2 Printing Date/Time in a Given Format Section 6.3 Representing Dates in Other Epochs Section 6.4 Converting YMDHMS to a Calendar or Epoch Seconds Section 6.5 Parsing Strings into Dates Section 6.6 Converting Epoch Seconds to DMYHMS Section 6.7 Adding to or Subtracting from a Dateor Calendar Section 6.8 Difference Between Two Dates Section 6.9 Comparing Dates Section 6.10 Day of Week/Month/Year or Week Number Section 6.11 Creating a Calendar Page Section 6.12 Measuring Elapsed Time Section 6.13 Sleeping for a While Section 6.14 Program: Reminder Service Chapter Structuring Data with Java Introduction Section 7.1 Using Arrays for Data Structuring Section 7.2 Resizing an Array Section 7.3 Like an Array, but More Dynamic Section 7.4 Using Iterators for Data-Independent Access Section 7.5 Structuring Data in a Linked List Section 7.6 Mapping with Hashtable and HashMap Section 7.7 Storing Strings in Properties and Preferences Section 7.8 Sorting a Collection Section 7.9 Avoiding the Urge to Sort Section 7.10 Eschewing Duplication Section 7.11 Finding an Object in a Collection Section 7.12 Converting a Collection to an Array Section 7.13 Rolling Your Own Iterator Section 7.14 Stack Section 7.15 Multidimensional Structures Section 7.16 Finally, Collections Section 7.17 Program: Timing Comparisons Chapter Data Structuring with Generics, foreach, and Enumerations (JDK 1.5) Introduction Section 8.1 Using Generic Collections Section 8.2 Using "foreach" Loops This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 8.3 Avoid Casting by Using Generics Section 8.4 Let Java Convert with AutoBoxing and AutoUnboxing Section 8.5 Using Typesafe Enumerations Section 8.6 Program: MediaInvoicer Chapter Object-Oriented Techniques Introduction Section 9.1 Printing Objects: Formatting with toString( ) Section 9.2 Overriding the Equals Method Section 9.3 Overriding the hashCode Method Section 9.4 The Clone Method Section 9.5 The Finalize Method Section 9.6 Using Inner Classes Section 9.7 Providing Callbacks via Interfaces Section 9.8 Polymorphism/Abstract Methods Section 9.9 Passing Values Section 9.10 Enforcing the Singleton Pattern Section 9.11 Roll Your Own Exceptions Section 9.12 Program: Plotter Chapter 10 Input and Output Introduction Section 10.1 Reading Standard Input Section 10.2 Writing Standard Output Section 10.3 Printing with the 1.5 Formatter Section 10.4 Scanning a File with StreamTokenizer Section 10.5 Scanning Input with the 1.5 Scanner Class Section 10.6 Opening a File by Name Section 10.7 Copying a File Section 10.8 Reading a File into a String Section 10.9 Reassigning the Standard Streams Section 10.10 Duplicating a Stream as It Is Written Section 10.11 Reading/Writing a Different Character Set Section 10.12 Those Pesky End-of-Line Characters Section 10.13 Beware Platform-Dependent File Code Section 10.14 Reading "Continued" Lines Section 10.15 Binary Data Section 10.16 Seeking Section 10.17 Writing Data Streams from C Section 10.18 Saving and Restoring Java Objects Section 10.19 Preventing ClassCastExceptions with SerialVersionUID Section 10.20 Reading and Writing JAR or Zip Archives Section 10.21 Reading and Writing Compressed Files Section 10.22 Program: Text to PostScript Chapter 11 Directory and Filesystem Operations Introduction Section 11.1 Getting File Information Section 11.2 Creating a File Section 11.3 Renaming a File Section 11.4 Deleting a File Section 11.5 Creating a Transient File Section 11.6 Changing File Attributes Section 11.7 Listing a Directory Section 11.8 Getting the Directory Roots Section 11.9 Creating New Directories This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 11.9 Creating New Directories Section 11.10 Program: Find Chapter 12 Programming External Devices: Serial and Parallel Ports Introduction Section 12.1 Choosing a Port Section 12.2 Opening a Serial Port Section 12.3 Opening a Parallel Port Section 12.4 Resolving Port Conflicts Section 12.5 Reading and Writing: Lock-Step Section 12.6 Reading and Writing: Event-Driven Section 12.7 Reading and Writing: Threads Section 12.8 Program: Penman Plotter Chapter 13 Graphics and Sound Introduction Section 13.1 Painting with a Graphics Object Section 13.2 Testing Graphical Components Section 13.3 Drawing Text Section 13.4 Drawing Centered Text in a Component Section 13.5 Drawing a Drop Shadow Section 13.6 Drawing Text with 2D Section 13.7 Drawing Text with an Application Font Section 13.8 Drawing an Image Section 13.9 Playing a Sound File Section 13.10 Playing a Video Clip Section 13.11 Printing in Java Section 13.12 Program: PlotterAWT Section 13.13 Program: Grapher Chapter 14 Graphical User Interfaces Introduction Section 14.1 Displaying GUI Components Section 14.2 Designing a Window Layout Section 14.3 A Tabbed View of Life Section 14.4 Action Handling: Making Buttons Work Section 14.5 Action Handling Using Anonymous Inner Classes Section 14.6 Terminating a Program with"Window Close" Section 14.7 Dialogs: When Later Just Won't Do Section 14.8 Catching and Formatting GUI Exceptions Section 14.9 Getting Program Output into a Window Section 14.10 Choosing a Value with JSpinner Section 14.11 Choosing a File with JFileChooser Section 14.12 Choosing a Color Section 14.13 Formatting JComponents with HTML Section 14.14 Centering a Main Window Section 14.15 Changing a Swing Program's Look and Feel Section 14.16 Enhancing Your GUI for Mac OS X Section 14.17 Program: Custom Font Chooser Section 14.18 Program: Custom Layout Manager Chapter 15 Internationalization and Localization Introduction Section 15.1 Creating a Button with I18N Resources Section 15.2 Listing Available Locales Section 15.3 Creating a Menu with I18N Resources Section 15.4 Writing Internationalization Convenience Routines This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 15.5 Creating a Dialog with I18N Resources Section 15.6 Creating a Resource Bundle Section 15.7 Extracting Strings from Your Code Section 15.8 Using a Particular Locale Section 15.9 Setting the Default Locale Section 15.10 Formatting Messages Section 15.11 Program: MenuIntl Section 15.12 Program: BusCard Chapter 16 Network Clients Introduction Section 16.1 Contacting a Server Section 16.2 Finding and Reporting Network Addresses Section 16.3 Handling Network Errors Section 16.4 Reading and Writing Textual Data Section 16.5 Reading and Writing Binary Data Section 16.6 Reading and Writing Serialized Data Section 16.7 UDP Datagrams Section 16.8 Program: TFTP UDP Client Section 16.9 Program: Telnet Client Section 16.10 Program: Chat Client Chapter 17 Server-Side Java: Sockets Introduction Section 17.1 Opening a Server for Business Section 17.2 Returning a Response (String or Binary) Section 17.3 Returning Object Information Section 17.4 Handling Multiple Clients Section 17.5 Serving the HTTP Protocol Section 17.6 Securing a Web Server with SSL and JSSE Section 17.7 Network Logging Section 17.8 Network Logging with log4j Section 17.9 Network Logging with JDK 1.4 Section 17.10 Finding Network Interfaces Section 17.11 Program: A Java Chat Server Chapter 18 Network Clients II: Applets and Web Clients Introduction Section 18.1 Embedding Java in a Web Page Section 18.2 Applet Techniques Section 18.3 Contacting a Server on the Applet Host Section 18.4 Making an Applet Show a Document Section 18.5 Making an Applet Run JavaScript Section 18.6 Making an Applet Run a CGI Script Section 18.7 Reading the Contents of a URL Section 18.8 URI, URL, or URN? Section 18.9 Extracting HTML from a URL Section 18.10 Extracting URLs from a File Section 18.11 Converting a Filename to a URL Section 18.12 Program: MkIndex Section 18.13 Program: LinkChecker Chapter 19 Java and Electronic Mail Introduction Section 19.1 Sending Email: Browser Version Section 19.2 Sending Email: For Real Section 19.3 Mail-Enabling a Server Program This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 19.3 Mail-Enabling a Server Program Section 19.4 Sending MIME Mail Section 19.5 Providing Mail Settings Section 19.6 Sending Mail Without Using JavaMail Section 19.7 Reading Email Section 19.8 Program: MailReaderBean Section 19.9 Program: MailClient Chapter 20 Database Access Introduction Section 20.1 Easy Database Access with JDO Section 20.2 Text-File Databases Section 20.3 DBM Databases Section 20.4 JDBC Setup and Connection Section 20.5 Connecting to a JDBC Database Section 20.6 Sending a JDBC Query and Getting Results Section 20.7 Using JDBC Prepared Statements Section 20.8 Using Stored Procedures with JDBC Section 20.9 Changing Data Using a ResultSet Section 20.10 Storing Results in a RowSet Section 20.11 Changing Data Using SQL Section 20.12 Finding JDBC Metadata Section 20.13 Program: SQLRunner Chapter 21 XML Introduction Section 21.1 Generating XML from Objects Section 21.2 Transforming XML with XSLT Section 21.3 Parsing XML with SAX Section 21.4 Parsing XML with DOM Section 21.5 Verifying Structure with a DTD Section 21.6 Generating Your Own XML with DOM Section 21.7 Program: xml2mif Chapter 22 Distributed Java: RMI Introduction Section 22.1 Defining the RMI Contract Section 22.2 Creating an RMI Client Section 22.3 Creating an RMI Server Section 22.4 Deploying RMI Across a Network Section 22.5 Program: RMI Callbacks Section 22.6 Program: NetWatch Chapter 23 Packages and Packaging Introduction Section 23.1 Creating a Package Section 23.2 Documenting Classes with Javadoc Section 23.3 Beyond JavaDoc: Annotations/Metadata (JDK 1.5) and XDoclet Section 23.4 Archiving with jar Section 23.5 Running an Applet from a JAR Section 23.6 Running an Applet with a Modern JDK Section 23.7 Running a Main Program from a JAR Section 23.8 Preparing a Class as a JavaBean Section 23.9 Pickling Your Bean into a JAR Section 23.10 Packaging a Servlet into a WAR File Section 23.11 "Write Once, Install Anywhere" Section 23.12 "Write Once, Install on Mac OS X" This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 23.13 Java Web Start Section 23.14 Signing Your JAR File Chapter 24 Threaded Java Introduction Section 24.1 Running Code in a Different Thread Section 24.2 Displaying a Moving Image with Animation Section 24.3 Stopping a Thread Section 24.4 Rendezvous and Timeouts Section 24.5 Synchronizing Threads with the synchronized Keyword Section 24.6 Simplifying Synchronization with 1.5 Locks Section 24.7 Synchronizing Threads with wait( ) and notifyAll( ) Section 24.8 Simplifying Producer-Consumer with the 1.5 Queue Interface Section 24.9 Background Saving in an Editor Section 24.10 Program: Threaded Network Server Section 24.11 Simplifying Servers Using the Concurrency Utilities (JDK 1.5) Chapter 25 Introspection, or "A Class Named Class" Introduction Section 25.1 Getting a Class Descriptor Section 25.2 Finding and Using Methods and Fields Section 25.3 Loading and Instantiating a Class Dynamically Section 25.4 Constructing a Class from Scratch Section 25.5 Performance Timing Section 25.6 Printing Class Information Section 25.7 Program: CrossRef Section 25.8 Program: AppletViewer Chapter 26 Using Java with Other Languages Introduction Section 26.1 Running a Program Section 26.2 Running a Program and Capturing Its Output Section 26.3 Mixing Java and Scripts with BSF Section 26.4 Marrying Java and Perl Section 26.5 Blending in Native Code (C/C++) Section 26.6 Calling Java from Native Code Section 26.7 Program: DBM Afterword Colophon Index < Day Day Up > ... commands are javac to compile and java to run your program (and, on Windows only, javaw to run a program without a console window) For example: C:javasrc>javac HelloWorld .java C:javasrc >java HelloWorld... end, the Java Enterprise Edition (J2EE) is concerned with building large, scalable, distributed applications Servlets, JavaServer Pages, JavaServer Faces, CORBA, RMI, JavaMail, Enterprise JavaBeans©... O'Reilly Media, Inc The Cookbook series designations, Java Cookbook, the image of a domestic chicken, and related trade dress are trademarks of O'Reilly Media, Inc Java and all Java- based trademarks