Java Cookbook
Total Page:16
File Type:pdf, Size:1020Kb
www.it-ebooks.info www.it-ebooks.info THIRD EDITION Java Cookbook Ian F. Darwin www.it-ebooks.info 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] www.it-ebooks.info 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 www.it-ebooks.info 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 www.it-ebooks.info 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 www.it-ebooks.info 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 www.it-ebooks.info 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.