
- •Contents at a Glance
- •Contents
- •About the Authors
- •About the Technical Reviewer
- •Acknowledgments
- •Introduction
- •Oracle Java Certifications: Overview
- •FAQ 1. What are the different levels of Oracle Java certification exams?
- •FAQ 4. Is OCPJP 7 prerequisite for other Oracle certification exams?
- •FAQ 5. Should I take the OCPJP 7 or OCPJP 6 exam?
- •The OCPJP 7 Exam
- •FAQ 7. How many questions are there in the OCPJP 7 exam?
- •FAQ 8. What is the duration of the OCPJP 7 exam?
- •FAQ 9. What is the cost of the OCPJP 7 exam?
- •FAQ 10. What are the passing scores for the OCPJP 7 exam?
- •FAQ 11. What kinds of questions are asked in the OCPJP 7 exam?
- •FAQ 12. What does the OCPJP 7 exam test for?
- •FAQ 13. I’ve been a Java programmer for last five years. Do I have to prepare for the OCPJP 7 exam?
- •FAQ 14. How do I prepare for the OCPJP 7 exam?
- •FAQ 15. How do I know when I’m ready to take the OCPJP 7 exam?
- •Taking the OCPJP 7 Exam
- •FAQ 16. What are my options to register for the exam?
- •FAQ 17. How do I register for the exam, schedule a day and time for taking the exam, and appear for the exam?
- •The OCPJP 7 Exam: Pretest
- •Answers with Explanations
- •Post-Pretest Evaluation
- •Essentials of OOP
- •FunPaint Application: An Example
- •Foundations of OOP
- •Abstraction
- •Encapsulation
- •Inheritance
- •Polymorphism
- •Class Fundamentals
- •Object Creation
- •Constructors
- •Access Modifiers
- •Public Access Modifier
- •Private Access Modifier
- •Protected and Default Access Modifier
- •Overloading
- •Method Overloading
- •Constructor Overloading
- •Overload resolution
- •Points to Remember
- •Inheritance
- •Runtime Polymorphism
- •An Example
- •Overriding Issues
- •Overriding: Deeper Dive
- •Invoking Superclass Methods
- •Type Conversions
- •Upcasts and Downcasts
- •Casting Between Inconvertible Types
- •Using “instanceof” for Safe Downcasts
- •Java Packages
- •Working with Packages
- •Static Import
- •Summary
- •Abstract Classes
- •Points to Remember
- •Using the “final” Keyword
- •Final Classes
- •Final Methods and Variables
- •Points to Remember
- •Using the “static” Keyword
- •Static Block
- •Points to Remember
- •Flavors of Nested Classes
- •Static Nested Classes (or Interfaces)
- •Points to Remember
- •Inner Classes
- •Points to Remember
- •Local Inner Classes
- •Points to Remember
- •Anonymous Inner Classes
- •Points to Remember
- •Enum Data Types
- •Points to Remember
- •Summary
- •Interfaces
- •Declaring and Using Interfaces
- •Points to Remember
- •Abstract Classes vs. Interfaces
- •Choosing Between an Abstract Class and an Interface
- •Object Composition
- •Composition vs. Inheritance
- •Points to Remember
- •Design Patterns
- •The Singleton Design Pattern
- •Ensuring That Your Singleton Is Indeed a Singleton
- •The Factory Design Pattern
- •Differences Between Factory and Abstract Factory Design Patterns
- •The Data Access Object (DAO) Design Pattern
- •Points to Remember
- •Summary
- •Generics
- •Using Object Type and Type Safety
- •Using the Object Class vs. Generics
- •Container Implementation Using the Object Class
- •Container Implementation Using Generics
- •Creating Generic Classes
- •Diamond Syntax
- •Interoperability of Raw Types and Generic Types
- •Generic Methods
- •Generics and Subtyping
- •Wildcard Parameters
- •Limitations of Wildcards
- •Bounded Wildcards
- •Wildcards in the Collections Class
- •Points to Remember
- •The Collections Framework
- •Why Reusable Classes?
- •Basic Components of the Collections Framework
- •Abstract Classes and Interfaces
- •Concrete Classes
- •List Classes
- •ArrayList Class
- •The ListIterator Interface
- •The LinkedList Class
- •The Set Interface
- •The HashSet Class
- •The TreeSet Class
- •The Map Interface
- •The HashMap Class
- •Overriding the hashCode() Method
- •The NavigableMap Interface
- •The Queue Interface
- •The Deque Interface
- •Comparable and Comparator Interfaces
- •Algorithms (Collections Class)
- •The Arrays Class
- •Methods in the Arrays Class
- •Array as a List
- •Points to Remember
- •Summary
- •Generics
- •Collections Framework
- •Processing Strings
- •String Searching
- •The IndexOf() Method
- •The regionMatches() Method
- •String Parsing
- •String Conversions
- •The Split() Method
- •Regular Expressions
- •Understanding regex Symbols
- •Regex Support in Java
- •Searching and Parsing with regex
- •Replacing Strings with regex
- •String Formatting
- •Format Specifiers
- •Points to Remember
- •Summary
- •Reading and Writing from Console
- •Understanding the Console Class
- •Formatted I/O with the Console Class
- •Special Character Handling in the Console Class
- •Using Streams to Read and Write Files
- •Character Streams and Byte Streams
- •Character Streams
- •Reading Text Files
- •Reading and Writing Text Files
- •“Tokenizing” Text
- •Byte Streams
- •Reading a Byte Stream
- •Data Streams
- •Writing to and Reading from Object Streams: Serialization
- •Serialization: Some More Details
- •Points to Remember
- •Summary
- •A Quick History of I/O APIs
- •Using the Path Interface
- •Getting Path Information
- •Comparing Two Paths
- •Using the Files Class
- •Checking File Properties and Metadata
- •Copying a File
- •Moving a File
- •Deleting a File
- •Walking a File Tree
- •Revisiting File Copy
- •Finding a File
- •Watching a Directory for Changes
- •Points to Remember
- •Summary
- •Introduction to JDBC
- •The Architecture of JDBC
- •Two-Tier and Three-Tier JDBC Architecture
- •Types of JDBC Drivers
- •Setting Up the Database
- •Connecting to a Database Using a JDBC Driver
- •The Connection Interface
- •Connecting to the Database
- •Statement
- •ResultSet
- •Querying the Database
- •Updating the Database
- •Getting the Database Metadata
- •Points to Remember
- •Querying and Updating the Database
- •Performing Transactions
- •Rolling Back Database Operations
- •The RowSet Interface
- •Points to Remember
- •Summary
- •Define the Layout of the JDBC API
- •Connect to a Database by Using a JDBC driver
- •Update and Query a Database
- •Customize the Transaction Behavior of JDBC and Commit Transactions
- •Use the JDBC 4.1 RowSetProvider, RowSetFactory, and RowSet Interfaces
- •Introduction to Exception Handling
- •Throwing Exceptions
- •Unhandled Exceptions
- •Try and Catch Statements
- •Programmatically Accessing the Stack Trace
- •Multiple Catch Blocks
- •Multi-Catch Blocks
- •General Catch Handlers
- •Finally Blocks
- •Points to Remember
- •Try-with-Resources
- •Closing Multiple Resources
- •Points to Remember
- •Exception Types
- •The Exception Class
- •The RuntimeException Class
- •The Error Class
- •The Throws Clause
- •Method Overriding and the Throws Clause
- •Points to Remember
- •Custom Exceptions
- •Assertions
- •Assert Statement
- •How Not to Use Asserts
- •Summary
- •Introduction
- •Locales
- •The Locale Class
- •Getting Locale Details
- •Resource Bundles
- •Using PropertyResourceBundle
- •Using ListResourceBundle
- •Loading a Resource Bundle
- •Naming Convention for Resource Bundles
- •Formatting for Local Culture
- •The NumberFormat Class
- •The Currency Class
- •The DateFormat Class
- •The SimpleDateFormat Class
- •Points to Remember
- •Summary
- •Introduction to Concurrent Programming
- •Important Threading-Related Methods
- •Creating Threads
- •Extending the Thread Class
- •Implementing the Runnable Interface
- •The Start( ) and Run( ) Methods
- •Thread Name, Priority, and Group
- •Using the Thread.sleep() Method
- •Using Thread’s Join Method
- •Asynchronous Execution
- •The States of a Thread
- •Two States in “Runnable” State
- •Concurrent Access Problems
- •Data Races
- •Thread Synchronization
- •Synchronized Blocks
- •Synchronized Methods
- •Synchronized Blocks vs. Synchronized Methods
- •Deadlocks
- •Other Threading Problems
- •Livelocks
- •Lock Starvation
- •The Wait/Notify Mechanism
- •Let’s Solve a Problem
- •More Thread States
- •timed_waiting and blocked States
- •waiting State
- •Using Thread.State enum
- •Understanding IllegalThreadStateException
- •Summary
- •Using java.util.concurrent Collections
- •Semaphore
- •CountDownLatch
- •Exchanger
- •CyclicBarrier
- •Phaser
- •Concurrent Collections
- •Apply Atomic Variables and Locks
- •Atomic Variables
- •Locks
- •Conditions
- •Multiple Conditions on a Lock
- •Use Executors and ThreadPools
- •Executor
- •Callable, Executors, ExecutorService, ThreadPool, and Future
- •ThreadFactory
- •The ThreadLocalRandom Class
- •TimeUnit Enumeration
- •Use the Parallel Fork/Join Framework
- •Useful Classes of the Fork/Join Framework
- •Using the Fork/Join Framework
- •Points to Remember
- •Summary
- •Using java.util.concurrent Collections
- •Applying Atomic Variables and Locks
- •Using Executors and ThreadPools
- •Using the Parallel Fork/Join Framework
- •Chapter 3: Java Class Design
- •Chapter 4: Advanced Class Design
- •Chapter 5: Object-Oriented Design Principles
- •Chapter 6: Generics and Collections
- •Chapter 7: String Processing
- •Chapter 8: Java I/O Fundamentals
- •Chapter 9: Java File I/O (NIO.2)
- •Chapter 10: Building Database Applications with JDBC
- •Chapter 11: Exceptions and Assertions
- •Chapter 12: Localization
- •Chapter 13: Threads
- •Chapter 14: Concurrency
- •OCPJP7 Exam (1Z0-804 a.k.a. Java SE 7 Programmer II) Topics
- •OCPJP 7 Exam (1Z0-805, a.k.a. Upgrade to Java SE 7 Programmer) Topics
- •Answers and Explanations
- •Answer Sheet
- •Answers and Explanations
- •Index

Chapter 8 ■ Java I/O Fundamentals
(Note that you’re setting the delimiter and not the pattern that you want to match). The program makes use of a TreeSet<String> to store the read strings. The program reads words from the underlying stream, checks if it is a non-empty string, and adds the lower-case versions of the string to the TreeSet. Since the data structure is a TreeSet, it removes duplicates; remember that it’s a Set, which does not allow duplicates. Further, it is also an ordered data structure, meaning that it maintains an “ordering” of values inserted, which in this case is an alphabetical ordering of Strings. Hence the program correctly prints the words from given text file that contained a limerick.
Byte Streams
In this section, you’ll explore I/O with byte streams. You’ll first learn how to read and write data files, and also how to stream objects, store them in files and then read them back. The class of OutputStream and its derived classes are shown in Figure 8-4; InputStream and its derived classes are shown in Figure 8-5.
|
DataOutput |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
OutputStream |
|
|
|
|
|||
|
(interface) |
|
|
|
|
|
|
|
|
|
|
|
||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ObjectOutput(interface) |
|
|
PipedOutputStream |
|
FilterOutputStream |
|
FileOutputStream |
|||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ObjectOutputStream
DataOutputStream BufferedOutputStream
Figure 8-4. Important classes deriving from the OutputStream abstract class
|
DataInput |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
InputStream |
|
|
|
|
|
|
|
|||
|
(interface) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ObjectInput (interface) |
|
|
|
PipedInputStream |
|
|
FilterInputStream |
|
|
FileInputStream |
|
||||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ObjectInputStream |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|||
|
|
|
DataInputStream |
|
|
BufferedInputStream |
|
PushbackInputStream |
|||||||||||||
|
|
|
|
|
|
|
|
|
|
||||||||||||
|
|
|
|
|
|
|
|
|
|
||||||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Figure 8-5. Important classes deriving from the InputStream abstract class
Table 8-5 summarizes the important classes of InputStream and OutputStream.
237
Chapter 8 ■ Java I/O Fundamentals
Table 8-5. Important Classes Deriving from the InputStream and OutputStream Classes
|
|
Class name |
Short description |
PipedInputStream, |
PipedInputStream and PipedOutputStream create a communication channel |
PipedOutputStream |
on which data can be sent and received. PipedOutputStream sends the data and |
|
PipedInputStream receives the data sent on the channel. |
FileInputStream, |
FileInputStream receives a byte stream from a file, FileOutputStream writes a |
FileOutputStream |
byte stream into a file. |
FilterInputStream, |
These filtered streams are used to add functionalities to plain streams. The output |
FilterOutputStream |
of an InputStream can be filtered using FilterInputStream. The output of an |
|
OutputStream can be filtered using FilterOutputStream. |
BufferedInputStream, |
BufferedInputStream adds buffering capabilities to an input stream. |
BufferedOutputStream |
BufferedOutputStream adds buffering capabilities to an output stream. |
PushbackInputStream |
A subclass of FilterInputStream, it adds “pushback” functionality to an input stream. |
DataInputStream, |
DataInputStream can be used to read java primitive data types from an input stream. |
DataOutputStream |
DataOutputStream can be used to write Java primitive data types to an output stream. |
|
|
Reading a Byte Stream
Byte streams are used for processing files that do not contain human-readable text. For example, a Java source file has human readable content, but a .class file does not. A .class file is meant for processing by the JVM, hence you must use byte streams to process the .class file.
The contents of a .class file are written in a specific file format, described in the specification of the Java Virtual Machine. Don’t worry; you’re not going to understand this complex file format, but you’ll just check its “magic number.” Each file format has a magic number used to quickly check the file format. For example “.MZ” is the magic number (or more properly, magic string) for .exe files in Windows. Similarly, the .class files have the magic number “0xCAFEBABE”, written as a hexadecimal value. These magic numbers are typically written as first few bytes of a variable length file format.
To understand how byte streams work, you’ll just check if the given file starts with the magic number “0xCAFEBABE” (Listing 8-7). If so, it could be a valid .class file; if not, it’s certainly not a .class file.
Listing 8-7. ClassFileMagicNumberChecker.java
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException;
import java.util.Arrays;
//check if the passed file is a valid .class file or not.
//note that this is an elementary version of a checker that checks if the given file
//is a valid file that is written according to the JVM specification
//it checks only the magic number
class ClassFileMagicNumberChecker {
public static void main(String []args) { if(args.length != 1) {
System.err.println("Pass a valid file name as argument"); System.exit(−1);
}
238
Chapter 8 ■ Java I/O Fundamentals
String fileName = args[0];
//create a magicNumber byte array with values for four bytes in 0xCAFEBABE
//you need to have an explicit down cast to byte since
//the hex values like 0xCA are of type int
byte []magicNumber = {(byte) 0xCA, (byte)0xFE, (byte)0xBA, (byte)0xBE}; try (FileInputStream fis = new FileInputStream(fileName)) {
//magic number is of 4 bytes –
//use a temporary buffer to read first four bytes byte[] u4buffer = new byte[4];
//read a buffer full (4 bytes here) of data from the file if(fis.read(u4buffer) != −1) { // if read was successful
//the overloaded method equals for two byte arrays
//checks for equality of contents if(Arrays.equals(magicNumber, u4buffer)) {
System.out.printf("The magic number for passed file %s matches that of a .class file", fileName);
}
else {
System.out.printf("The magic number for passed file %s does not match that of a .class file", fileName);
}
}
} catch(FileNotFoundException fnfe) {
System.err.println("file does not exist with the given file name "); } catch(IOException ioe) {
System.err.println("an I/O error occurred while processing the file");
}
}
}
Let’s first see if it works by passing the source (.java) file and the .class file for the same program.
D:> java ClassFileMagicNumberChecker ClassFileMagicNumberChecker.java
The magic number for passed file ClassFileMagicNumberChecker.java does not match that of a .class file D:\> java ClassFileMagicNumberChecker ClassFileMagicNumberChecker.class
The magic number for passed file ClassFileMagicNumberChecker.class matches that of a .class file
Yes, it works. The classes InputStream and OutputStream form the base of the hierarchies for byte streams. You perform file I/O, so open the given file as a FileInputStream. You need to check the first four bytes, so you read four bytes in a temporary buffer. You need to compare the contents of this buffer against the sequence of bytes 0xCA, 0xFE, 0xBA, and 0xBE. If the contents of these two arrays are not equal, then the passed file is not a .class file.
In this program, you directly manipulate the underlying byte stream using a FileInputStream. In case you need to speed up the program when you read large number of bytes, you can use a buffered output stream, as in
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName));
Similar to these input streams, you can use output streams to write sequence of bytes to a data file. You can use
FileOutputStream and BufferedOutputStream for that.
239
Chapter 8 ■ Java I/O Fundamentals
After reading this program, didn’t you think that reading an array of four bytes and comparing the contents of the byte arrays was awkward (instead of directly comparing the contents of an integer)? In other words, 0xCAFEBABE is an integer value, and you could read this value directly as an integer value and compare it against the read integer value. For this, you need to use data streams, which provide methods like readInt(), which we’ll discuss now.
Data Streams
To understand how to write or read with byte streams, let’s write a simple program that writes and then reads constant values to a data file (see Listing 8-8). To keep the problem simple, you will write only the values 0 to 9 in the form of the following primitive type values: byte, short, int, long, float, and double.
Listing 8-8. DataStreamExample.java
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException;
//A simple class to illustrate data streams; write constants 0 and 1 in different data type values
//into a file and read the results back and print them
class DataStreamExample {
public static void main(String []args) {
// write some data into a data file with hard-coded name "temp.data" try (DataOutputStream dos =
new DataOutputStream(new FileOutputStream("temp.data"))) {
//write values 1 to 10 as byte, short, int, long, float and double
//omitting boolean type because an int value cannot
//be converted to boolean
for(int i = 0; i < 10; i++) { dos.writeByte(i); dos.writeShort(i); dos.writeInt(i); dos.writeLong(i); dos.writeFloat(i); dos.writeDouble(i);
}
} catch(FileNotFoundException fnfe) {
System.err.println("cannot create a file with the given file name "); System.exit(−1); // don't proceed – exit the program
} catch(IOException ioe) {
System.err.println("an I/O error occurred while processing the file"); System.exit(−1); // don't proceed – exit the program
}
//the DataOutputStream will auto-close, so don't have to worry about it
//now, read the written data and print it to console
try (DataInputStream dis = new DataInputStream(new FileInputStream("temp.data"))) {
//the order of values to read is byte, short, int, long, float and
//double
//since we've written from 0 to 0, the for loop has to run 10 times
240
Chapter 8 ■ Java I/O Fundamentals
for(int i = 0; i < 10; i++) {
//%d is for printing byte, short, int or long
//%f, %g, or %e is for printing float or double
//%n is for printing newline System.out.printf("%d %d %d %d %g %g %n",
dis.readByte(),
dis.readShort(),
dis.readInt(),
dis.readLong(),
dis.readFloat(),
dis.readDouble());
}
} catch(FileNotFoundException fnfe) {
System.err.println("cannot create a file with the given file name "); } catch(IOException ioe) {
System.err.println("an I/O error occurred while processing the file"); } // the DataOutputStream will auto-close, so don't have to worry about it
}
}
First, let’s see if it works by executing the program.
D:> java DataStreamExample 0 0 0 0 0.000000 0.000000 1 1 1 1 1.000000 1.000000 2 2 2 2 2.000000 2.000000 3 3 3 3 3.000000 3.000000 4 4 4 4 4.000000 4.000000 5 5 5 5 5.000000 5.000000 6 6 6 6 6.000000 6.000000 7 7 7 7 7.000000 7.000000 8 8 8 8 8.000000 8.000000 9 9 9 9 9.000000 9.000000
Yes, it works. Now, as mentioned earlier, the contents of data files are not human-readable. In this case, you’re writing values 0 to 9 as various primitive type values into the temporary file write named temp.data. If you try to open this data file and see the contents, you won’t be able to recognize or understand what it contains. Here’s an example of its contents:
D:>type temp.data
|
|
|
• • |
• |
•?Ç |
?• |
|
• • |
• |
•@ |
@ |
• • |
• |
•@@ |
• • |
• |
•@Ç |
@• |
• |
• |
• |
•@á |
@¶ |
• • |
• |
•@• |
@• |
|
@• @• |
|
A |
|
@ |
|
|
|
|
A• |
@" |
|
|
|
|
|
|
|
|
The typed contents of the file temp.data look like garbage values because the primitive type values like the integer values 0 or 9 are stored in terms of bytes. However, the type command in Windows tries to convert these bytes into human-readable characters, hence the output does not make any sense. The data will make sense only if we know the format of the data stored in the file and read it according to that format.
241