Copyright
Table of Contents
Index
Full Description
About the Author
Reviews
Reader reviews
Errata
Java Cookbook
Ian Darwin
Publisher: O'Reilly
First Edition June 2001
ISBN: 0-59600-170-3, 882 pages
This book offers Java developers short, focused pieces of code that
are easy to incorporate into other programs. The idea is to focus on
things that are useful, tricky, or both. The book's code segments
cover all of the dominant APIs and should serve as a great "jumping-
off place" for Java developers who want to get started in areas
outside their specialization.
Java Cookbook
Preface
Who This Book Is For
What's in This Book?
Platform Notes
Other Books
Conventions Used in This Book
2.5 Writing Operating System-Dependent Code
2.6 Using CLASSPATH Effectively
2.7 Using Extensions or Other Packaged APIs
2.8 Parsing Command-Line Arguments
3. Strings and Things
3.1 Introduction
3.2 Taking Strings Apart with Substrings
3.3 Taking Strings Apart with StringTokenizer
3.4 Putting Strings Together with + and StringBuffer
3.5 Processing a String One Character at a Time
3.6 Aligning Strings
3.7 Converting Between Unicode Characters and Strings
3.8 Reversing a String by Word or Character
3.9 Expanding and Compressing Tabs
3.10 Controlling Case
3.11 Indenting Text Documents
3.12 Entering Non-Printable Characters
3.13 Trimming Blanks from the End of a String
3.14 Parsing Comma-Separated Data
3.15 Program: A Simple Text Formatter
3.16 Program: Soundex Name Comparisons
4. Pattern Matching with Regular Expressions
4.1 Introduction
4.2 Regular Expression Syntax
4.3 How REs Work in Practice
4.4 Using Regular Expressions in Java
4.5 Testing REs Interactively
4.6 Finding the Matching Text
5.21 Program: Number Palindromes
6. Dates and Times
6.1 Introduction
6.2 Finding Today's Date
6.3 Printing Date/Time in a Specified Format
6.4 Representing Dates in Other Epochs
6.5 Converting YMDHMS to a Calendar or Epoch Seconds
6.6 Parsing Strings into Dates
6.7 Converting Epoch Seconds to DMYHMS
6.8 Adding to or Subtracting from a Date or Calendar
6.9 Difference Between Two Dates
6.10 Comparing Dates
6.11 Day of Week/Month/Year or Week Number
6.12 Calendar Page
6.13 High-Resolution Timers
6.14 Sleeping for a While
6.15 Program: Reminder Service
7. Structuring Data with Java
7.1 Introduction
7.2 Data Structuring Using Arrays
7.3 Resizing an Array
7.4 Like an Array, but More Dynamic
7.5 Data-Independent Access with Iterators
7.6 Structuring Data in a Linked List
7.7 Mapping with Hashtable and HashMap
7.8 Storing Strings in Properties and Preferences
7.9 Sorting a Collection
7.10 Sorting in Java 1.1
9.6 Reading a File into a String
9.7 Reassigning the Standard Streams
9.8 Duplicating a Stream as It Is Written
9.9 Reading/Writing a Different Character Set
9.10 Those Pesky End-of-Line Characters
9.11 Beware Platform-Dependent File Code
9.12 Reading "Continued" Lines
9.13 Scanning a File
9.14 Binary Data
9.15 Seeking
9.16 Writing Data Streams from C
9.17 Saving and Restoring Serialized Objects
9.18 Preventing ClassCastExceptions with SerialVersionUID
9.19 Reading and Writing JAR or Zip Archives
9.20 Reading and Writing Compressed Files
9.21 Program: Text to PostScript
9.22 Program: TarList (File Converter)
10. Directory and Filesystem Operations
10.1 Introduction
10.2 Getting File Information
10.3 Creating a File
10.4 Renaming a File
10.5 Deleting a File
10.6 Creating a Transient File
10.7 Changing File Attributes
10.8 Listing a Directory
10.9 Getting the Directory Roots
10.10 Making New Directories
10.11 Program: Find
13.2 Displaying GUI Components
13.3 Designing a Window Layout
13.4 A Tabbed View of Life
13.5 Action Handling: Making Buttons Work
13.6 Action Handling Using Anonymous Inner Classes
13.7 Terminating a Program with "Window Close"
13.8 Dialogs: When Later Just Won't Do
13.9 Getting Program Output into a Window
13.10 Choosing a File with JFileChooser
13.11 Choosing a Color
13.12 Centering a Main Window
13.13 Changing a Swing Program's Look and Feel
13.14 Program: Custom Font Chooser
13.15 Program: Custom Layout Manager
14. Internationalization and Localization
14.1 Introduction
14.2 Creating a Button with I18N Resources
14.3 Listing Available Locales
14.4 Creating a Menu with I18N Resources
14.5 Writing Internationalization Convenience Routines
14.6 Creating a Dialog with I18N Resources
14.7 Creating a Resource Bundle
14.8 JILTing Your Code
14.9 Using a Particular Locale
14.10 Setting the Default Locale
14.11 Formatting Messages
14.12 Program: MenuIntl
14.13 Program: BusCard
17.8 Extracting HTML from a URL
17.9 Extracting URLs from a File
17.10 Converting a Filename to a URL
17.11 Program: MkIndex
17.12 Program: LinkChecker
18. Web Server Java: Servlets and JSP
18.1 Introduction
18.2 First Servlet: Generating an HTML Page
18.3 Servlets: Processing Form Parameters
18.4 Cookies
18.5 Session Tracking
18.6 Generating PDF from a Servlet
18.7 HTML Meets Java: JSP
18.8 JSP Include/Forward
18.9 JavaServer Pages Using a Servlet
18.10 Simplifying Your JSP with a JavaBean
18.11 JSP Syntax Summary
18.12 Program: CookieCutter
18.13 Program: JabaDot Web News Portal
19. Java and Electronic Mail
19.1 Introduction
19.2 Sending Email: Browser Version
19.3 Sending Email: For Real
19.4 Mail-Enabling a Server Program
19.5 Sending MIME Mail
19.6 Providing Mail Settings
19.7 Sending Mail Without Using JavaMail
19.8 Reading Email
22.4 RMI Server
22.5 Deploying RMI Across a Network
22.6 Program: RMI Callbacks
22.7 Program: RMIWatch
23. Packages and Packaging
23.1 Introduction
23.2 Creating a Package
23.3 Documenting Classes with Javadoc
23.4 Archiving with jar
23.5 Running an Applet from a JAR
23.6 Running an Applet with a JDK
23.7 Running a Program from a JAR
23.8 Preparing a Class as a JavaBean
23.9 Pickling Your Bean into a JAR
23.10 Packaging a Servlet into a WAR File
23.11 "Write Once, Install Anywhere"
23.12 Java Web Start
23.13 Signing Your JAR File
24. Threaded Java
24.1 Introduction
24.2 Running Code in a Different Thread
24.3 Displaying a Moving Image with Animation
24.4 Stopping a Thread
24.5 Rendezvous and Timeouts
24.6 Thread Communication: Synchronized Code
24.7 Thread Communication: wait( ) and notifyAll( )
24.8 Background Saving in an Editor
24.9 Threaded Network Server
I sent an email to the address Greg provided, and got this mail back:
From scndprsn.Eng.Sun.COM!jag Wed Mar 29 19:43:54 1995
Date: Wed, 29 Mar 1995 16:47:51 +0800
From: (James Gosling)
To: ,
Subject: Re: WebRunner
Cc:
Content-Length: 361
Status: RO
X-Lines: 9
> Hi. A friend told me about WebRunner(?), your extensible network
> browser. It and Oak(?) its extention language, sounded neat. Can
> you please tell me if it's available for play yet, and/or if any
> papers on it are available for FTP?
Check out
(oak got renamed to java and webrunner got renamed to
hotjava to keep the lawyers happy)
I downloaded HotJava and began to play with it. At first I wasn't sure about this newfangled
language, which looked like a mangled 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 (as often
the programs would have the same name). And as I learned more about Java, I began to see its
advantages for many kinds of work, such as the automatic memory reclaim and the elimination of
pointer calculations. The javasrc directory kept growing. I wrote a Java course for Learning Tree,
and the directory kept growing faster, reaching the point where it needed subdirectories. Even
then, it became increasingly difficult to find things, and it soon became evident that some kind of
documentation was needed.
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
But Java is suited to a different range of tasks than Perl. Perl (and other scripting languages such
as awk and Python) are particularly suited to the "one-liner" utility task. As Tom and Nathan
show, Perl excels at things like printing the 42nd line from 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 2 was aimed at this type of development. However, I will necessarily
illustrate many techniques with shorter examples and even code fragments. Be assured that
every line of code you 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 1) 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 book itself was
partly composed in XML, a recent simplification that builds upon a decade of experience in SGML
(the parent standard that led to the tag-based syntax of HTML). It is not clear at this point if XML
will primarily be useful as a publishing format or as a data manipulation format, or if its prevalence
will further blur that distinction, though it seems that the blurring of distinctions is more likely.
However, I used XML here to type in and mark up the original text of some of the chapters of this
book. The text was then converted to FrameMaker input by the XmlForm program. This program
also handles -- by use of another program, GetMark -- full 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 to getting it to adapt to the surrounding countryside -- the 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, and rearrange
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 and pattern-matching problem domains. This is the first chapter that covers
often need to generate electronic mail, so this section ends with Chapter 19.
Chapter 20 covers the Java Database Connectivity package (JDBC), showing how you can
connect to local or remote relational databases, store and retrieve data, and find out information
about 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 apply using SAX and DOM, two standard Java APIs.
Chapter 22 takes the distributed notion one step further and discusses Remote Methods
Invocation, Java's standard remote procedure call mechanism. RMI lets you build clients, servers,
and even "callback" scenarios, using a standard Java mechanism -- the Interface -- to describe
the contract between client and server.
Chapter 23 shows how to create packages of classes that work together. This chapter also talks
about "deploying" or distributing and installing your software.
Chapter 24 tells you how to write classes that appear to do more than one thing at a time and let
you take advantage of powerful multiprocessor hardware.
Chapter 25 lets you in on such big secrets as how to write API cross reference documents
mechanically and how web browsers are able to load any old applet -- never having seen that
particular class before -- and run it.
Sometimes you already have code written and working in another language that can do part of
your work for you, or you want 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++.
There isn't room in an 800-page book for everything I'd like to tell you about Java. The Chapter
27 presents some closing thoughts and a link to my online summary of Java APIs that every Java
developer should know about.
No two programmers or writers will agree on the best order for presenting all the Java topics. To
help you find your way around, there are extensive cross-references, mostly by recipe number.
Platform Notes
In its short history, Java has gone through four major versions. The first official release is known
as Java JDK 1.0, and its last bug-fixed version is 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 the time you read
[1]
Kaffe, the Swedish word for coffee, is an open source (GNU Public License) Java implementation that
runs on just about any Unix or Unix-like system, and has been ported to other platforms such as Win32.
The Java API consists of two parts, core APIs and non-core APIs. The core is, by definition,
what's included in the JDK that you download for free from . Non-core is
everything else. But even this "core" is far from tiny: it weighs in at around 50 packages and well
over a thousand public classes, each with up to 30 or more public methods. Programs that stick
to this core API are reasonably assured of portability to any Java 2 platform.
The non-core APIs are further divided into standard extensions and non-standard extensions. All
standard extensions have package names beginning with javax.,
[2]
and reference
implementations are available from Sun. A Java licensee (like, say, Apple or Microsoft) is not
required to implement every standard extension, but if they do, the interface of the standard
extension should be adhered to. This book will call your attention to any code that depends on a
standard extension. There is little code that depends on non-standard extensions other than code
listed in the book itself (the major exception is the Regular Expressions API used in Chapter 4).
My own package, com.darwinsys.util, contains some utility classes used here and there;
you will see an import for this at the top of any file that uses classes from it.
[2]
Note that not all packages named javax. are extensions: javax.swing and its sub-packages -- the
Swing GUI packages -- used to be extensions, but are now core.
Other Books
There is a lot of useful information 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 & Associates publishes one of the largest -- and, I think, 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 in the back pages of this book
Section 25.8), but he doesn't show you how to write a book like mine.
General Programming Books
Donald E. Knuth's The Art of Computer Programming has been a source of inspiration to
students of computing since its first publication by Addison Wesley in 1968. Volume 1 covers
Fundamental Algorithms, Volume 2 is Seminumerical Algorithms, and Volume 3 is Sorting and
Searching. The remaining four volumes in the projected series were never 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 30 years ago.
[3]
[3]
With apologies for algorithm decisions that are less relevant today given the massive changes in
computing power now available.
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. Brian
Kernighan also wrote (with P. J. Plauger) 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 somewhat 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 by Rob Pike) to the Software Tools series. This book
continues the Bell Labs (now part of Lucent) tradition of excellence in software textbooks. I have
even adapted one bit of code from their book, in Section 3.14.
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."
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.
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 & Associates, Inc.
101 Morris Street
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:
There is an O'Reilly web site for the book, listing errata, examples, or any additional information.
You can access this page at:
I also have a personal web site for the book:
Both sites will 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 in again! For specific
instructions, see the next section.
Getting the Source Code
From my web site , just follow the Download link and you will
be presented with three choices:
1. Download the entire source archive as a single large zip file
2. Download individual source files, indexed alphabetically as well as by chapter
3. Download the binary JAR file for the com.darwinsys.util package needed to compile
many of the other programs
"just now" available for download, is the prized first entry in my saved Java mailbox. Mike Rozek
took me on as a Learning Tree 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 had previously been used in my Java course notes. Finally,
thanks to the many Learning Tree instructors and students who showed me ways of improving
my presentations. I still teach for "The Tree" and recommend their courses for the busy developer
who wants to zero in on one topic in detail over four days. Their web site is
.
Closer to this project, Tim O'Reilly believed in "the little Lint book" when it was just a sample
chapter, enabling my early entry into the circle of O'Reilly authors. Years later, Mike Loukides
encouraged me to keep trying to find a Java book idea that both he and I could work with. And he
stuck by me when I kept falling behind the deadlines. Mike also read the entire manuscript and
made many sensible comments, some of which brought flights of fancy down to earth. Jessamyn
Read turned many faxed and emailed scratchings of dubious legibility into the quality illustrations
you see in this book. And many, many other talented people at O'Reilly & Associates helped put
this book into the form in which you now see it.
I also must thank my reviewers, first and foremost my dear wife Betty Cerar, who may still think
Java is some kind of caffeinated beverage that I drink while programming, but whose passion for
clear expression and correct grammar has benefited much of my writing. Jonathan Knudsen,
Andy Oram, and David Flanagan commented on the outline when it was little more than a list of
chapters and recipes, and yet were able to see the kind of book it could become, and to suggest
ways to make it better. Learning Tree instructor Jim Burgess read most of the book with a very
critical eye on locution, formulation, and code. Bil Lewis and Mike Slinn ()
made helpful comments on multiple drafts of the book. Ron Hitchens () and
Marc Loy carefully read the entire final draft. Editor Sue Miller helped shepherd the manuscript
through the somewhat energetic final phases of production. Sarah Slocombe read the XML
chapter in its entirety and made many lucid suggestions, though unfortunately time did not permit
me to include all of them. Each of these people made this book better in many ways, particularly
by suggesting additional recipes or revising existing ones. Any faults that remain are surely my
Development Environment (IDE) way. Then I'll discuss a few details about applets, in case you
are working on them. Deprecation warnings come next, as you're likely to meet them in
maintaining "old" Java code.
[1]
[1]
There is humor in the phrase "old Java code," which should be apparent when you realize that Java has
been in circulation for under five years at the time of this book's first printing.
If you're already happy with your IDE, you may wish to skip some or all of this material. It's here
to ensure that everybody can compile and debug their programs before we move on.
1.2 Compiling and Running Java: JDK
1.2.1 Problem
You need to compile and run your Java program.
1.2.2 Solution
This is one of the few areas where your computer's operating system impinges into Java's
portability, so let's get it out of the way first.
1.2.2.1 JDK
Using the command-line Java Development Kit (JDK) may be the best way to keep up with the
very latest improvements from Sun/JavaSoft. This is not the fastest compiler available by any
means; the compiler is written in Java and interpreted at compile time, making it a sensible
bootstrapping solution, but not necessarily optimal for speed of development. Nonetheless, using
Sun's JDK (or Java SDK), the commands are javac to compile and java to run your program. For
example:
C:\javasrc>javac HelloWorld.java
C:\javasrc>java HelloWorld
Hello, World
C:\javasrc>
As you can see from the compiler's (lack of) output, this compiler works on the Unix "no news is
command-line options, many that are the same as the JDK compiler's, but some that go beyond
them. See Jikes's online documentation for details.
An older C++-based Java compiler, Guavac, is not considered finished. Indeed, its author has
stopped maintaining it. Nonetheless, I was able to use Guavac 1.2 to compile many of the
examples in this book (note that the Guavac version number of 1.2 is unrelated to the Sun JDK
version number 1.2). See information on Guavac.
Another alternative technology is Kaffe, a product that Transvirtual
() licenses but also makes available in open source form under
the standard GNU Public License. Kaffe aims to be a complete JDK replacement, though it has
moved rather slowly past the JDK 1.1 level and is, as of this writing, still not quite a complete
Java 2 clone. Again, on OpenBSD there is a port, and on Linux there are RPMs available. Visit
Transvirtual's web site for the latest information on Kaffe.
One last freeware package is Japhar, a Java runtime clone, available from
.
1.2.2.3 MacOS
The JDK is purely command-line-based. At the other end of the spectrum in terms of keyboard-
versus-visual, we have the Apple Macintosh. Whole books have been written about how great the
Mac is, and I won't step into that debate. I will, however, comment on how lamentable it is that
Apple let its Java implementation lag behind current standards. Users of MacOS 8 and 8.5 have
put up with Java 1.8 for several years. MacOS X (Release 10 of MacOS) is a new technology
base built upon a BSD Unix base. As such, it has a regular command line as well as all the
traditional Mac tools. And it features a full Java 2 implementation, including Swing.
For MacOS 8, if you've followed Apple's directions for installing the MacOS Runtime for Java
(MRJ), you can compile by dragging a file to, or double-clicking on, the "javac" icon (I've made
aliases for this icon and friends on my desktop). Once the dialog shown in Figure 1-1 appears,
you can click on "Do Javac" (or just press Enter on the keyboard), first changing any options if
you want.
Figure 1-1. MacOS 8 Javac window
You will then see the Java console window stating that it ran javac (as shown in Figure 1-2).
editor with Java support. Tools such as TextPad (), Visual Slick Edit,
and others are low-cost windowed editors (primarily for MS-Windows) that have some amount of
Java recognition built in, and the ability to compile from within the editor. TextPad has quite a
number of file types that it recognizes, including batch files and shell scripts, C, C++, Java, JSP
(see Section 18.7), JavaScript (a client-side web technology), and many others. For each of
these, it uses color highlighting to show which part of the file being edited comprises keywords,
comments, quoted strings, and so on. This is very useful in spotting when part of your code has
been swallowed up by an unterminated /* comment or a missing quote. While this isn't the same
as the deep understanding of Java that a full IDE might possess, experience has shown that it
definitely aids programmer productivity. TextPad also has a "compile Java" command and a "run
external program" command. Both of these have the advantage of capturing the entire command
output into a window, which may be easier to scroll than a command-line window on some
platforms. On the other hand, you don't see the command results until the program terminates,
which can be most uncomfortable if your GUI application throws an exception before it puts up its
main window. Despite this minor drawback, TextPad is a very useful tool. Other editors that
include color highlighting include vim (an enhanced version of the Unix tool vi, available for MS-
Windows and Unix platforms; see ), the ever-popular Emacs editor, and
many others.
1.4 Compiling, Running, and Testing with an IDE
1.4.1 Problem
Several tools are too many.
1.4.2 Solution
Use an integrated development environment.
1.4.3 Discussion
Many programmers find that using a handful of separate tools -- a text editor, a compiler, and a
runner program, not to mention a debugger (see Section 1.13) -- is too many. An integrated
development environment (IDE
[2]
) integrates all of these into a single toolset with a (hopefully
consistent) graphical user interface. There are many IDEs to choose from, ranging from text