ebook img

Java Cookbook PDF

896 Pages·2014·14.105 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Java Cookbook

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 (http://my.safaribooksonline.com). For more information, contact our corporate/ institutional sales department: 800-998-9938 or [email protected]. Editors: Mike Loukides and Meghan Blanchette Indexer: Lucie Haskins Production Editor: Melanie Yarbrough Cover Designer: Randy Comer Copyeditor: Kim Cofer Interior Designer: David Futato Proofreader: Jasmine Kwityn Illustrator: Rebecca Demarest June 2014: Third Edition Revision History for the Third Edition: 2014-06-20: First release See http://oreilly.com/catalog/errata.csp?isbn=9781449337049 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] Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. Getting Started: Compiling, Running, and Debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1. Compiling and Running Java: JDK 2 1.2. Editing and Compiling with a Syntax-Highlighting Editor 3 1.3. Compiling, Running, and Testing with an IDE 4 1.4. Using CLASSPATH Effectively 14 1.5. Downloading and Using the Code Examples 17 1.6. Automating Compilation with Apache Ant 22 1.7. Automating Dependencies, Compilation, Testing, and Deployment with Apache Maven 25 1.8. Automating Dependencies, Compilation, Testing, and Deployment with Gradle 29 1.9. Dealing with Deprecation Warnings 31 1.10. Conditional Debugging Without #ifdef 33 1.11. Maintaining Program Correctness with Assertions 35 1.12. Debugging with JDB 36 1.13. Avoiding the Need for Debuggers with Unit Testing 38 1.14. Maintaining Your Code with Continuous Integration 41 1.15. Getting Readable Tracebacks 45 1.16. Finding More Java Source Code: Programs, Frameworks, Libraries 46 2. Interacting with the Environment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 2.1. Getting Environment Variables 51 2.2. Getting Information from System Properties 52 2.3. Learning About the Current JDK Release 54 2.4. Dealing with Operating System–Dependent Variations 55 2.5. Using Extensions or Other Packaged APIs 58 iii 2.6. Parsing Command-Line Arguments 59 3. Strings and Things. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 3.1. Taking Strings Apart with Substrings 69 3.2. Breaking Strings Into Words 70 3.3. Putting Strings Together with StringBuilder 74 3.4. Processing a String One Character at a Time 76 3.5. Aligning Strings 78 3.6. Converting Between Unicode Characters and Strings 81 3.7. Reversing a String by Word or by Character 83 3.8. Expanding and Compressing Tabs 84 3.9. Controlling Case 89 3.10. Indenting Text Documents 90 3.11. Entering Nonprintable Characters 91 3.12. Trimming Blanks from the End of a String 92 3.13. Parsing Comma-Separated Data 93 3.14. Program: A Simple Text Formatter 98 3.15. Program: Soundex Name Comparisons 100 4. Pattern Matching with Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 4.1. Regular Expression Syntax 107 4.2. Using regexes in Java: Test for a Pattern 114 4.3. Finding the Matching Text 117 4.4. Replacing the Matched Text 120 4.5. Printing All Occurrences of a Pattern 121 4.6. Printing Lines Containing a Pattern 123 4.7. Controlling Case in Regular Expressions 125 4.8. Matching “Accented” or Composite Characters 126 4.9. Matching Newlines in Text 127 4.10. Program: Apache Logfile Parsing 129 4.11. Program: Data Mining 131 4.12. Program: Full Grep 133 5. Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 5.1. Checking Whether a String Is a Valid Number 141 5.2. Storing a Larger Number in a Smaller Number 143 5.3. Converting Numbers to Objects and Vice Versa 144 5.4. Taking a Fraction of an Integer Without Using Floating Point 146 5.5. Ensuring the Accuracy of Floating-Point Numbers 147 5.6. Comparing Floating-Point Numbers 149 5.7. Rounding Floating-Point Numbers 151 5.8. Formatting Numbers 152 iv | Table of Contents 5.9. Converting Between Binary, Octal, Decimal, and Hexadecimal 154 5.10. Operating on a Series of Integers 155 5.11. Working with Roman Numerals 157 5.12. Formatting with Correct Plurals 161 5.13. Generating Random Numbers 163 5.14. Calculating Trigonometric Functions 165 5.15. Taking Logarithms 166 5.16. Multiplying Matrices 167 5.17. Using Complex Numbers 169 5.18. Handling Very Large Numbers 171 5.19. Program: TempConverter 174 5.20. Program: Number Palindromes 175 6. Dates and Times—New API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 6.1. Finding Today’s Date 182 6.2. Formatting Dates and Times 183 6.3. Converting Among Dates/Times, YMDHMS, and Epoch Seconds 185 6.4. Parsing Strings into Dates 186 6.5. Difference Between Two Dates 187 6.6. Adding to or Subtracting from a Date or Calendar 188 6.7. Interfacing with Legacy Date and Calendar Classes 189 7. Structuring Data with Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 7.1. Using Arrays for Data Structuring 192 7.2. Resizing an Array 193 7.3. The Collections Framework 195 7.4. Like an Array, but More Dynamic 196 7.5. Using Generic Collections 199 7.6. Avoid Casting by Using Generics 200 7.7. How Shall I Iterate Thee? Let Me Enumerate the Ways 204 7.8. Eschewing Duplicates with a Set 206 7.9. Using Iterators or Enumerations for Data-Independent Access 207 7.10. Structuring Data in a Linked List 208 7.11. Mapping with Hashtable and HashMap 212 7.12. Storing Strings in Properties and Preferences 214 7.13. Sorting a Collection 218 7.14. Avoiding the Urge to Sort 222 7.15. Finding an Object in a Collection 224 7.16. Converting a Collection to an Array 226 7.17. Rolling Your Own Iterator 227 7.18. Stack 230 7.19. Multidimensional Structures 234 Table of Contents | v 7.20. Program: Timing Comparisons 236 8. Object-Oriented Techniques. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 8.1. Formatting Objects for Printing with toString() 241 8.2. Overriding the equals() and hashCode() Methods 243 8.3. Using Shutdown Hooks for Application Cleanup 248 8.4. Using Inner Classes 250 8.5. Providing Callbacks via Interfaces 251 8.6. Polymorphism/Abstract Methods 255 8.7. Passing Values 256 8.8. Using Typesafe Enumerations 259 8.9. Enforcing the Singleton Pattern 263 8.10. Roll Your Own Exceptions 266 8.11. Using Dependency Injection 267 8.12. Program: Plotter 270 9. Functional Programming Techniques: Functional Interfaces, Streams, Parallel Collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 9.1. Using Lambdas/Closures Instead of Inner Classes 278 9.2. Using Lambda Predefined Interfaces Instead of Your Own 282 9.3. Simplifying Processing with Streams 283 9.4. Improving Throughput with Parallel Streams and Collections 285 9.5. Creating Your Own Functional Interfaces 286 9.6. Using Existing Code as Functional with Method References 289 9.7. Java Mixins: Mixing in Methods 293 10. Input and Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 10.1. Reading Standard Input 298 10.2. Reading from the Console or Controlling Terminal; Reading Passwords Without Echoing 300 10.3. Writing Standard Output or Standard Error 302 10.4. Printing with Formatter and printf 304 10.5. Scanning Input with StreamTokenizer 308 10.6. Scanning Input with the Scanner Class 312 10.7. Scanning Input with Grammatical Structure 316 10.8. Opening a File by Name 317 10.9. Copying a File 318 10.10. Reading a File into a String 325 10.11. Reassigning the Standard Streams 325 10.12. Duplicating a Stream as It Is Written 326 10.13. Reading/Writing a Different Character Set 329 10.14. Those Pesky End-of-Line Characters 330 vi | Table of Contents 10.15. Beware Platform-Dependent File Code 331 10.16. Reading “Continued” Lines 332 10.17. Reading/Writing Binary Data 336 10.18. Seeking to a Position within a File 337 10.19. Writing Data Streams from C 338 10.20. Saving and Restoring Java Objects 340 10.21. Preventing ClassCastExceptions with SerialVersionUID 344 10.22. Reading and Writing JAR or ZIP Archives 346 10.23. Finding Files in a Filesystem-Neutral Way with getResource() and getResourceAsStream() 349 10.24. Reading and Writing Compressed Files 351 10.25. Learning about the Communications API for Serial and Parallel Ports 352 10.26. Save User Data to Disk 357 10.27. Program: Text to PostScript 360 11. Directory and Filesystem Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365 11.1. Getting File Information 365 11.2. Creating a File 368 11.3. Renaming a File 369 11.4. Deleting a File 370 11.5. Creating a Transient File 372 11.6. Changing File Attributes 373 11.7. Listing a Directory 375 11.8. Getting the Directory Roots 377 11.9. Creating New Directories 378 11.10. Using Path instead of File 379 11.11. Using the FileWatcher Service to Get Notified about File Changes 380 11.12. Program: Find 382 12. Media: Graphics, Audio, Video. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387 12.1. Painting with a Graphics Object 388 12.2. Showing Graphical Components Without Writing Main 389 12.3. Drawing Text 390 12.4. Drawing Centered Text in a Component 391 12.5. Drawing a Drop Shadow 393 12.6. Drawing Text with 2D 395 12.7. Drawing Text with an Application Font 397 12.8. Drawing an Image 400 12.9. Reading and Writing Images with javax.imageio 404 12.10. Playing an Audio/Sound File 405 12.11. Playing a Video File 406 12.12. Printing in Java 411 Table of Contents | vii 12.13. Program: PlotterAWT 415 12.14. Program: Grapher 417 13. Network Clients. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421 13.1. Contacting a Server 423 13.2. Finding and Reporting Network Addresses 424 13.3. Handling Network Errors 426 13.4. Reading and Writing Textual Data 427 13.5. Reading and Writing Binary Data 430 13.6. Reading and Writing Serialized Data 432 13.7. UDP Datagrams 433 13.8. Program: TFTP UDP Client 436 13.9. URI, URL, or URN? 441 13.10. REST Web Service Client 442 13.11. SOAP Web Service Client 444 13.12. Program: Telnet Client 448 13.13. Program: Chat Client 450 13.14. Program: Simple HTTP Link Checker 454 14. Graphical User Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457 14.1. Displaying GUI Components 458 14.2. Run Your GUI on the Event Dispatching Thread 460 14.3. Designing a Window Layout 462 14.4. A Tabbed View of Life 464 14.5. Action Handling: Making Buttons Work 465 14.6. Action Handling Using Anonymous Inner Classes 467 14.7. Action Handling Using Lambdas 469 14.8. Terminating a Program with “Window Close” 470 14.9. Dialogs: When Later Just Won’t Do 475 14.10. Catching and Formatting GUI Exceptions 477 14.11. Getting Program Output into a Window 480 14.12. Choosing a Value with JSpinner 486 14.13. Choosing a File with JFileChooser 487 14.14. Choosing a Color 489 14.15. Formatting JComponents with HTML 492 14.16. Centering a Main Window 493 14.17. Changing a Swing Program’s Look and Feel 496 14.18. Enhancing Your Swing GUI for Mac OS X 500 14.19. Building Your GUI Application with JavaFX 503 14.20. Program: Custom Font Chooser 505 viii | Table of Contents

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.