javacookbook.pdf - THIRD EDITION Java Cookbook Ian F Darwin Java Cookbook Third Edition by Ian F Darwin Copyright 2014 RejmiNet Group Inc All rights

javacookbook.pdf - THIRD EDITION Java Cookbook Ian F Darwin...

This preview shows page 1 out of 898 pages.

You've reached the end of your free preview.

Want to read all 898 pages?

Unformatted text preview: THIRD EDITION Java Cookbook Ian F. Darwin Java Cookbook, Third Edition by Ian F. Darwin Copyright © 2014 RejmiNet Group, Inc.. All rights reserved. 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 ( ). For more information, contact our corporate/ institutional sales department: 800-998-9938 or [email protected] Editors: Mike Loukides and Meghan Blanchette Production Editor: Melanie Yarbrough Copyeditor: Kim Cofer Proofreader: Jasmine Kwityn June 2014: Indexer: Lucie Haskins Cover Designer: Randy Comer Interior Designer: David Futato Illustrator: Rebecca Demarest Third Edition Revision History for the Third Edition: 2014-06-20: First release 2014-07-23: Second release See for release details. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Java Cookbook, the cover image of a domestic chicken, and related trade dress are trademarks of O’Reilly Media, 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 author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 978-1-449-33704-9 [LSI] In Memoriam Andrej Cerar Darwin 1989-2014 Son, friend, and fellow craftsman. Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv 1. Getting Started: Compiling, Running, and Debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1. Compiling and Running Java: JDK 1.2. Editing and Compiling with a Syntax-Highlighting Editor 1.3. Compiling, Running, and Testing with an IDE 1.4. Using CLASSPATH Effectively 1.5. Downloading and Using the Code Examples 1.6. Automating Compilation with Apache Ant 1.7. Automating Dependencies, Compilation, Testing, and Deployment with Apache Maven 1.8. Automating Dependencies, Compilation, Testing, and Deployment with Gradle 1.9. Dealing with Deprecation Warnings 1.10. Conditional Debugging Without #ifdef 1.11. Maintaining Program Correctness with Assertions 1.12. Debugging with JDB 1.13. Avoiding the Need for Debuggers with Unit Testing 1.14. Maintaining Your Code with Continuous Integration 1.15. Getting Readable Tracebacks 1.16. Finding More Java Source Code: Programs, Frameworks, Libraries 2 3 4 14 17 22 25 29 31 33 35 36 38 41 45 46 2. Interacting with the Environment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 2.1. Getting Environment Variables 2.2. Getting Information from System Properties 2.3. Learning About the Current JDK Release 2.4. Dealing with Operating System–Dependent Variations 2.5. Using Extensions or Other Packaged APIs 51 52 54 55 58 v 2.6. Parsing Command-Line Arguments 59 3. Strings and Things. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 3.1. Taking Strings Apart with Substrings 3.2. Breaking Strings Into Words 3.3. Putting Strings Together with StringBuilder 3.4. Processing a String One Character at a Time 3.5. Aligning Strings 3.6. Converting Between Unicode Characters and Strings 3.7. Reversing a String by Word or by Character 3.8. Expanding and Compressing Tabs 3.9. Controlling Case 3.10. Indenting Text Documents 3.11. Entering Nonprintable Characters 3.12. Trimming Blanks from the End of a String 3.13. Parsing Comma-Separated Data 3.14. Program: A Simple Text Formatter 3.15. Program: Soundex Name Comparisons 69 70 74 76 78 81 83 84 89 90 91 92 93 98 100 4. Pattern Matching with Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 4.1. Regular Expression Syntax 4.2. Using regexes in Java: Test for a Pattern 4.3. Finding the Matching Text 4.4. Replacing the Matched Text 4.5. Printing All Occurrences of a Pattern 4.6. Printing Lines Containing a Pattern 4.7. Controlling Case in Regular Expressions 4.8. Matching “Accented” or Composite Characters 4.9. Matching Newlines in Text 4.10. Program: Apache Logfile Parsing 4.11. Program: Data Mining 4.12. Program: Full Grep 107 114 117 120 121 123 125 126 127 129 131 133 5. Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 5.1. Checking Whether a String Is a Valid Number 5.2. Storing a Larger Number in a Smaller Number 5.3. Converting Numbers to Objects and Vice Versa 5.4. Taking a Fraction of an Integer Without Using Floating Point 5.5. Ensuring the Accuracy of Floating-Point Numbers 5.6. Comparing Floating-Point Numbers 5.7. Rounding Floating-Point Numbers 5.8. Formatting Numbers vi | Table of Contents 141 143 144 146 147 149 151 152 5.9. Converting Between Binary, Octal, Decimal, and Hexadecimal 5.10. Operating on a Series of Integers 5.11. Working with Roman Numerals 5.12. Formatting with Correct Plurals 5.13. Generating Random Numbers 5.14. Calculating Trigonometric Functions 5.15. Taking Logarithms 5.16. Multiplying Matrices 5.17. Using Complex Numbers 5.18. Handling Very Large Numbers 5.19. Program: TempConverter 5.20. Program: Number Palindromes 154 155 157 161 163 165 166 167 169 171 174 175 6. Dates and Times—New API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 6.1. Finding Today’s Date 6.2. Formatting Dates and Times 6.3. Converting Among Dates/Times, YMDHMS, and Epoch Seconds 6.4. Parsing Strings into Dates 6.5. Difference Between Two Dates 6.6. Adding to or Subtracting from a Date or Calendar 6.7. Interfacing with Legacy Date and Calendar Classes 182 183 185 186 187 188 189 7. Structuring Data with Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 7.1. Using Arrays for Data Structuring 7.2. Resizing an Array 7.3. The Collections Framework 7.4. Like an Array, but More Dynamic 7.5. Using Generic Collections 7.6. Avoid Casting by Using Generics 7.7. How Shall I Iterate Thee? Let Me Enumerate the Ways 7.8. Eschewing Duplicates with a Set 7.9. Using Iterators or Enumerations for Data-Independent Access 7.10. Structuring Data in a Linked List 7.11. Mapping with Hashtable and HashMap 7.12. Storing Strings in Properties and Preferences 7.13. Sorting a Collection 7.14. Avoiding the Urge to Sort 7.15. Finding an Object in a Collection 7.16. Converting a Collection to an Array 7.17. Rolling Your Own Iterator 7.18. Stack 7.19. Multidimensional Structures Table of Contents 192 193 195 196 199 200 204 206 207 208 212 214 218 222 224 226 227 230 234 | vii 7.20. Program: Timing Comparisons 236 8. Object-Oriented Techniques. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 8.1. Formatting Objects for Printing with toString() 8.2. Overriding the equals() and hashCode() Methods 8.3. Using Shutdown Hooks for Application Cleanup 8.4. Using Inner Classes 8.5. Providing Callbacks via Interfaces 8.6. Polymorphism/Abstract Methods 8.7. Passing Values 8.8. Using Typesafe Enumerations 8.9. Enforcing the Singleton Pattern 8.10. Roll Your Own Exceptions 8.11. Using Dependency Injection 8.12. Program: Plotter 241 243 248 250 251 255 256 259 263 266 267 270 9. Functional Programming Techniques: Functional Interfaces, Streams, Parallel Collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 9.1. Using Lambdas/Closures Instead of Inner Classes 9.2. Using Lambda Predefined Interfaces Instead of Your Own 9.3. Simplifying Processing with Streams 9.4. Improving Throughput with Parallel Streams and Collections 9.5. Creating Your Own Functional Interfaces 9.6. Using Existing Code as Functional with Method References 9.7. Java Mixins: Mixing in Methods 278 282 283 285 286 289 293 10. Input and Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 10.1. Reading Standard Input 10.2. Reading from the Console or Controlling Terminal; Reading Passwords Without Echoing 10.3. Writing Standard Output or Standard Error 10.4. Printing with Formatter and printf 10.5. Scanning Input with StreamTokenizer 10.6. Scanning Input with the Scanner Class 10.7. Scanning Input with Grammatical Structure 10.8. Opening a File by Name 10.9. Copying a File 10.10. Reading a File into a String 10.11. Reassigning the Standard Streams 10.12. Duplicating a Stream as It Is Written 10.13. Reading/Writing a Different Character Set 10.14. Those Pesky End-of-Line Characters viii | Table of Contents 298 300 302 304 308 312 316 317 318 325 325 326 329 330 10.15. Beware Platform-Dependent File Code 10.16. Reading “Continued” Lines 10.17. Reading/Writing Binary Data 10.18. Seeking to a Position within a File 10.19. Writing Data Streams from C 10.20. Saving and Restoring Java Objects 10.21. Preventing ClassCastExceptions with SerialVersionUID 10.22. Reading and Writing JAR or ZIP Archives 10.23. Finding Files in a Filesystem-Neutral Way with getResource() and getResourceAsStream() 10.24. Reading and Writing Compressed Files 10.25. Learning about the Communications API for Serial and Parallel Ports 10.26. Save User Data to Disk 10.27. Program: Text to PostScript 331 332 336 337 338 340 344 346 349 351 352 357 360 11. Directory and Filesystem Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365 11.1. Getting File Information 11.2. Creating a File 11.3. Renaming a File 11.4. Deleting a File 11.5. Creating a Transient File 11.6. Changing File Attributes 11.7. Listing a Directory 11.8. Getting the Directory Roots 11.9. Creating New Directories 11.10. Using Path instead of File 11.11. Using the FileWatcher Service to Get Notified about File Changes 11.12. Program: Find 365 368 369 370 372 373 375 377 378 379 380 382 12. Media: Graphics, Audio, Video. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387 12.1. Painting with a Graphics Object 12.2. Showing Graphical Components Without Writing Main 12.3. Drawing Text 12.4. Drawing Centered Text in a Component 12.5. Drawing a Drop Shadow 12.6. Drawing Text with 2D 12.7. Drawing Text with an Application Font 12.8. Drawing an Image 12.9. Reading and Writing Images with javax.imageio 12.10. Playing an Audio/Sound File 12.11. Playing a Video File 12.12. Printing in Java 388 389 390 391 393 395 397 400 404 405 406 411 Table of Contents | ix 12.13. Program: PlotterAWT 12.14. Program: Grapher 415 417 13. Network Clients. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421 13.1. Contacting a Server 13.2. Finding and Reporting Network Addresses 13.3. Handling Network Errors 13.4. Reading and Writing Textual Data 13.5. Reading and Writing Binary Data 13.6. Reading and Writing Serialized Data 13.7. UDP Datagrams 13.8. Program: TFTP UDP Client 13.9. URI, URL, or URN? 13.10. REST Web Service Client 13.11. SOAP Web Service Client 13.12. Program: Telnet Client 13.13. Program: Chat Client 13.14. Program: Simple HTTP Link Checker 423 424 426 427 430 432 433 436 441 442 444 448 450 454 14. Graphical User Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457 14.1. Displaying GUI Components 14.2. Run Your GUI on the Event Dispatching Thread 14.3. Designing a Window Layout 14.4. A Tabbed View of Life 14.5. Action Handling: Making Buttons Work 14.6. Action Handling Using Anonymous Inner Classes 14.7. Action Handling Using Lambdas 14.8. Terminating a Program with “Window Close” 14.9. Dialogs: When Later Just Won’t Do 14.10. Catching and Formatting GUI Exceptions 14.11. Getting Program Output into a Window 14.12. Choosing a Value with JSpinner 14.13. Choosing a File with JFileChooser 14.14. Choosing a Color 14.15. Formatting JComponents with HTML 14.16. Centering a Main Window 14.17. Changing a Swing Program’s Look and Feel 14.18. Enhancing Your Swing GUI for Mac OS X 14.19. Building Your GUI Application with JavaFX 14.20. Program: Custom Font Chooser 14.21. Program: Custom AWT/Swing Layout Manager x | Table of Contents 458 460 462 464 465 467 469 470 475 477 480 486 487 489 492 493 496 500 503 505 510 15. Internationalization and Localization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517 15.1. Creating a Button with I18N Resources 15.2. Listing Available Locales 15.3. Creating a Menu with I18N Resources 15.4. Writing Internationalization Convenience Routines 15.5. Creating a Dialog with I18N Resources 15.6. Creating a Resource Bundle 15.7. Extracting Strings from Your Code 15.8. Using a Particular Locale 15.9. Setting the Default Locale 15.10. Formatting Messages with MessageFormat 15.11. Program: MenuIntl 15.12. Program: BusCard 518 520 521 521 523 525 526 527 528 529 531 533 16. Server-Side Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539 16.1. Opening a Server Socket for Business 16.2. Returning a Response (String or Binary) 16.3. Returning Object Information Across a Network Connection 16.4. Handling Multiple Clients 16.5. Serving the HTTP Protocol 16.6. Securing a Web Server with SSL and JSSE 16.7. Network Logging 16.8. Network Logging with SLF4J 16.9. Network Logging with log4j 16.10. Network Logging with java.util.logging 16.11. Finding Network Interfaces 16.12. Program: A Java Chat Server 540 542 546 547 552 554 557 558 561 563 565 567 17. Java and Electronic Mail. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573 17.1. Sending Email: Browser Version 17.2. Sending Email: For Real 17.3. Mail-Enabling a Server Program 17.4. Sending MIME Mail 17.5. Providing Mail Settings 17.6. Reading Email 17.7. Program: MailReaderBean 17.8. Program: MailClient 574 578 581 586 589 590 595 599 18. Database Access. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609 18.1. Easy Database Access with JPA and/or Hibernate 18.2. JDBC Setup and Connection 18.3. Connecting to a JDBC Database 611 616 619 Table of Contents | xi 18.4. Sending a JDBC Query and Getting Results 18.5. Using JDBC Prepared Statements 18.6. Using Stored Procedures with JDBC 18.7. Changing Data Using a ResultSet 18.8. Storing Results in a RowSet 18.9. Changing Data Using SQL 18.10. Finding JDBC Metadata 18.11. Program: SQLRunner 622 625 629 630 631 633 635 639 19. Processing JSON Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653 19.1. Generating JSON Directly 19.2. Parsing and Writing JSON with Jackson 19.3. Parsing and Writing JSON with org.json 655 656 657 20. Processing XML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661 20.1. Converting Between Objects and XML with JAXB 20.2. Converting Between Objects and XML with Serializers 20.3. Transforming XML with XSLT 20.4. Parsing XML with SAX 20.5. Parsing XML with DOM 20.6. Finding XML Elements with XPath 20.7. Verifying Structure with Schema or DTD 20.8. Generating Your Own XML with DOM and the XML Transformer 20.9. Program: xml2mif 664 667 668 671 673 677 678 681 683 21. Packages and Packaging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687 21.1. Creating a Package 21.2. Documenting Classes with Javadoc 21.3. Beyond Javadoc: Annotations/Metadata 21.4. Archiving with jar 21.5. Running a Program from a JAR 21.6. Preparing a Class as a JavaBean 21.7. Pickling Your Bean into a JAR 21.8. Packaging a Servlet into a WAR File 21.9. “Write Once, Install Anywhere” 21.10. “Write Once, Install on Mac OS X” 21.11. Java Web Start 21.12. Signing Your JAR File 688 689 693 695 696 699 702 704 705 705 707 714 22. Threaded Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717 22.1. Running Code in a Different Thread 22.2. Displaying a Moving Image with Animation xii | Table of Contents 719 724 22.3. Stopping a Thread 22.4. Rendezvous and Timeouts 22.5. Synchronizing Threads with the synchronized Keyword 22.6. Simplifying Synchronization with Locks 22.7. Synchronizing Threads the Hard Way with wait( ) and notifyAll( ) 22.8. Simplifying Producer/Consumer with the Queue Interface 22.9. Optimizing Parallel Processing with Fork/Join 22.10. Background Saving in an Editor 22.11. Program: Threaded Network Server 22.12. Simplifying Servers Using the Concurrency Utilities 728 731 732 738 742 748 750 754 755 762 23. Reflection, or “A Class Named Class”. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 765 23.1. Getting a Class Descriptor 23.2. Finding and Using Methods and Fields 23.3. Accessing Private Methods and Fields via Reflection 23.4. Loading and Instantiating a Class Dynamically 23.5. Constructing a Class from Scratch with a ClassLoader 23.6. Performance Timing 23.7. Printing Class Information 23.8. Listing Classes in a Package 23.9. Using and Defining Annotations 23.10. Finding Plug-in-like Classes via Annotations 23.11. Program: CrossRef 23.12. Program: AppletViewer 766 767 771 772 774 776 780 782 784 789 791 794 24. Using Java with Other Languages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 801 24.1. Running an External Program from Java 24.2. Running a Program and Capturing Its Output 24.3. Calling Other Languages via javax.script 24.4. Roll Your Own Scripting Engine 24.5. Marrying Java and Perl 24.6. Calling Other Languages via Native Code 24.7. Calling Java from Native Code 802 806 810 811 815 818 824 Afterword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 827 A. Java Then and Now. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 829 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 847 Table of Contents | xiii Preface Preface to the Third Edition Java 8 is the new kid on the block. Java 7 was a significant but incremental improvement over its predecessors. So much has changed since the previous edition of this book! What was “new in Java 5” has become ubiquitous in Java: annotations, generic types, concurrency utilities, and more. APIs have come and gone across the entire tableau of Java: JavaME is pretty much dead now that BlackBerry has abandoned it; JSF is (slowly) replacing JSP in parts of Enterprise Java; and Spring continues to expand its reach. Many people seem to think that “desktop Java” is dead or even that “Java is dying,” but it is definitely not rolling over yet; Swing, JavaFX, Java Enterprise, and (despite a major lawsuit by Oracle) Android are keeping the Java language very much alive. Additionally, a renewed interest in other “JVM languages” such as Groovy, JRuby, Jython, Scala, and Clojure is keeping the platform in the forefront of the development world. Indeed, the main challenge in preparing this third edition has been narrowing down the popular APIs, keeping my own excitement and biases in check, to make...
View Full Document

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

Stuck? We have tutors online 24/7 who can help you get unstuck.
A+ icon
Ask Expert Tutors You can ask You can ask You can ask (will expire )
Answers in as fast as 15 minutes