Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

ChaPTer 15 OCPJP 7 QuICk reFreSher

 

Iterable

Map

Iterator

 

Collection

SortedMap

ListIterator

 

 

NavigableMap

 

List

Set

Queue

 

 

SortedSet

Deque

 

 

NavigableSet

 

 

Figure 15-1. Important high-level java.util interfaces and their inheritance relationships

Implement the Comparable interface for your classes when a natural order is possible. If you want to compare the objects other than the natural order or if there is no natural ordering present for your class type, then create separate classes implementing the Comparator interface. Also, if you have multiple alternative ways to decide the order, then go for the

Comparator interface.

Chapter 7: String Processing

A regular expression defines a search pattern that can be used to execute operations such as string search and string manipulation. Table 15-1 summarizes commonly used symbols to specify regex, Table 15-2 lists commonly used metasymbols to specify regex, and Table 15-3 presents commonly used quantifiers with regex.

Table 15-1. Commonly Used Symbols to Specify Regular Expressions

Symbol Description

^expr

Matches the expr at the beginning of line.

expr$

Matches the expr at the end of line.

.

Matches any single character (except newline character).

[xyz]

Matches either x, y, or z.

[p-z]

Specifies a range. Matches any character from p to z.

[p-z1-9]

Matches either any character from p to z or any digit from 1 to 9

 

(remember, it won’t match p1).

[^p-z]

‘^’ as first character inside a bracket negates the pattern;

 

it matches any character except characters p to z.

Xy

Matches x followed by y.

x | y

Matches either x or y.

 

 

491

Chapter 15 OCPJP 7 Quick Refresher

Table 15-2.  Commonly Used Metasymbols to Specify Regular Expressions

Symbol Description

\d

Matches digits (equivalent to [0–9]).

\D

Matches non-digits.

\w

Matches word characters.

\W

Matches non-word characters.

\s

Matches whitespaces (equivalent to [\t\r\f\n]).

\S

Matches non-whitespaces.

\b

Matches word boundary when outside bracket. Matches backslash

 

when inside bracket.

\B

Matches non-word boundary.

\A

Matches beginning of string.

\Z

Matches end of string.

 

 

Table 15-3.  Commonly Used Quantifier Symbols

 

 

 

Symbol

Description

expr?

Matches 0 or 1 occurrence of expr (equivalent to expr{0,1}).

expr*

Matches 0 or more occurrences of expr (equivalent to expr{0,}).

expr+

Matches 1 or more occurrences of expr (equivalent to expr{1,}).

expr{x}

Matches x occurrences of expr.

expr{x, y}

Matches between x and y occurrences of expr.

expr{x,}

Matches x or more occurrences of expr.

 

 

 

The argument of the split() method is a delimiter string, which is a regular expression. If the regular expression you pass has invalid syntax, you’ll get a PatternSyntaxException exception.

Use the Pattern and Matcher classes whenever you are performing a search or replace on strings heavily; they are more efficient and faster than any other way to perform search/ replace in Java.

You can form groups within a regex. These groups can be used to specify quantifiers on a desired subset of the whole regex. These groups can also be used to specify back reference.

The method printf() (and the method format() in the String class) uses string formatting flags to format strings.

Each format specifier starts with the % sign; followed by flags, width, and precision information; and ending with a data type specifier. In this string, the flags, width, and precision information are optional while the % sign and data type specifier are mandatory. Table 15-4 shows the commonly used data type specifier symbols.

492

Chapter 15 OCPJP 7 Quick Refresher

Table 15-4.  Commonly Used Data Type Specifiers

Symbol Description

%b

Boolean

%c

Character

%d

Decimal integer (signed)

%e

Floating point number in scientific format

%f

Floating point number in decimal format

%g

Floating point number in decimal or scientific format

 

(depending on the value passed as argument)

%h

Hashcode of the passed argument

%n

Line separator (new line character)

%o

Integer formatted as an octal value

%s

String

%t

Date/time

%x

Integer formatted as an hexadecimal value

 

 

If you do not specify any string formatting specifier, the printf() method will not print anything from the given arguments!

Flags such as '-', '^', or '0' make sense only when you specify width with the format specifier string.

You can also print the % character in a format string; however, you need to use an escape sequence for it. In format specifier strings, % is an escape character, which means you need to use %% to print a single %.

If you do not provide the intended input data type as expected by the format string, you can get an IllegalFormatConversionException.

If you want to form a string and use it later rather than just printing it using the printf() method, you can use a static method in the String class, format().

Chapter 8: Java I/O Fundamentals

You can obtain reference to the console using the System.console() method; if the JVM is not associated with any console, this method will fail and return null.

Many methods are provided in Console-support formatted I/O. You can use the printf() and format() methods available in the Console class to print formatted text; the overloaded readLine() and readPassword() methods take format strings as arguments.

You can use character streams for text-based I/O and byte streams for data-based I/O.

493

Chapter 15 OCPJP 7 Quick Refresher

Character streams for reading and writing are called readers and writers, respectively (represented by the abstract classes Reader and Writer). Byte streams for reading and writing are called input streams and output streams, respectively (represented by the abstract classes

InputStream and OutputStream).

You can combine stream objects. You can create an object of BufferedInputStream that takes a FileInputStream object. In this way, the output of one stream is chained to the filtered stream. This is an important, useful, and elegant way to customize the stream based on your needs.

For processing data with primitive data types and Strings, you can use data streams.

Serialization is the process of converting the objects in memory into a series of bytes. You need to implement the Serializable interface in a class if you want to make the objects of the class serializable.

The Serializable interface is a marker interface. That means the Serializable interface does not declare any method inside it.

If you want to customize the process of serialization, you can implement the readObject() and writeObject() methods. Note that both of these methods are private methods, which means you are not overriding or overloading these methods. JVM checks the implementation of these methods and calls them instead of the usual methods. It sounds weird but it is the way the customization of the serialization process is implemented in the JVM.

A serialized object can be communicated over the network and deserialized on another machine. However, the class file of the object must be in the path of the destination machine, otherwise only the state of the object will be restored, not the whole object (i.e., you cannot invoke a method on the restored object).

You can create your own protocol for serialization. For that, you need to implement the Externalizable interface instead of the Serializable interface.

When you are not specifying serialVersionUID in a serialized class, JVM computes it for you. However, each JVM implementation has different mechanism to compute it; hence, it is not guaranteed that your serialized class will work on two different JVMs when you have not specified the serialVersionUID explicitly. Therefore, it is strongly recommended that you provide serialVersionUID in a class implementing the Serializable interface.

Chapter 9: Java File I/O (NIO.2)

A Path object is a programming abstraction to represent a path of a file/directory.

Do not confuse File with Files, Path with Paths, and FileSystem with FileSystems; they are different. File is an old class (Java 4) that represents file/directory path names, while Files was introduced in Java 7 as a utility class with comprehensive support for I/O APIs. The Path interface represents a file/directory path and defines a useful set of methods. However, the Paths class is a utility class that offers only two methods (both to get the Path object). FileSystems offer a list of factory methods for the class FileSystem, whereas FileSystem provides a useful set of methods to get information about a file system.

494

Chapter 15 OCPJP 7 Quick Refresher

The file or directory represented by a Path object might not exist.

Path provides two methods to use to compare Path objects: equals() and compareTo(). Even if two Path objects point to the same file/directory, it is not guaranteed that you will get true from the equals() method. You need to make sure that both are absolute and normalized paths for an equality comparison to succeed for paths.

You can check the existence of a file using the exists() method of the Files class.

You can retrieve attributes of a file using the getAttributes() method. You can use the readAttributes() method of the Files class to read attributes of a file in bulk.

While copying, all the directories (except the last one if you are copying a directory) in the specified path must exist to avoid NoSuchFileException.

If you copy a directory using the copy() method, it will not copy the files/directories contained in the source directory; you need to explicitly copy them to the destination folder.

It is not necessary that you perform copy on two files/directories only. You can take input from an InputStream and write to a file; similarly, you can take input from a file and copy to an

OutputStream. You can use the methods copy(InputStream, Path, CopyOptions...) and copy(Path, OutputStream, CopyOptions...).

Use the delete() method to delete a file; use the deleteIfExists() method to delete a file only if it exists.

If you do not want to implement all four methods in the FileVisitor interface, you can simply extend your implementation from the SimpleFileVisitor class.

The PathMatcher interface is useful when you want to find a file satisfying a certain pattern. You can specify the pattern using glob or regex. Table 15-5 summarizes the patterns supported by the Glob syntax.

Table 15-5.  Patterns Supported by Glob Syntax

Pattern Description

*

Matches any string of any length, even zero length.

**

Similar to “*” but it crosses directory boundaries.

?

Matches to any single character.

[xyz]

Matches to either x, y, or z.

[0-5]

Matches to any character from the range 0 to 5.

[a-z]

Matches to any lowercase letter.

{xyz, abc}

Matches to either xyz or abc.

 

 

Java 7 offers a directory watch service that can notify you when the file you are working on is changed by some other program. You can register a Path object using a watch service along with certain event types. Whenever any file in the specified directory changes, an event is sent to the registered program.

You must be careful performing an operation while walking a file tree. For instance, if you are performing a recursive delete, then you should first delete all the containing files before deleting the directory that is holding these containing files.

495

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]