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

Chapter 8 Java I/O Fundamentals

Note that nothing was displayed in the console when typing the password. Why is Arrays.fill(password, ' '); in this program? It is a recommended practice to “empty” the read password string once its use is over; here you use Array’s fill() method for this purpose. This is a secure programming practice to avoid malicious reads of program data to discover password strings. In fact, unlike the readLine() method, which returns a String, the readPassword() method returns a char array. With a char array, as soon as the password is validated, it is possible to empty it and remove the trace of the password text from memory; with a String object, which is garbage collected, it is not as easy as with a char array.

Special Character Handling in the Console Class

Writing text through Console’s printf() or format() methods has the advantage that these methods handle special characters better than printing text through PrintStream. (We’ll discuss streams in more detail in the next section.) Listing 8-3 shows an example.

Listing 8-3.  SpecialCharHandling.java

import java.io.Console;

// better to print thro' Console object - it handles "special characters" better class SpecialCharHandling {

public static void main(String []args) {

//string has three Scandinavian characters String scandString = "å, ä, and ö";

//try printing scandinavian characters directly with println System.out.println("Printing scands directly with println: " + scandString);

//now, get the Console object and print scand characters thro' that Console console = System.console();

console.printf("Printing scands thro' console's printf method: " + scandString);

}

}

Here is what this program prints:

Printing scands directly with println: •, •, and ÷

Printing scands thro' console's printf method: å, ä, and ö

As you can see from this output, Console’s printf() method (and other methods) have better support for special characters.

Using Streams to Read and Write Files

What are streams? Streams are ordered sequences of data. Java deals with input and output in terms of streams. For example, when you read a sequence of bytes from a binary file, you’re reading from an input stream; similarly, when you write a sequence of bytes to a binary file, you’re writing to an output stream. Note how we referred to reading or writing bytes from binary files, but what about reading or writing characters from text files? Java differentiates between processing text and binary data. Before delving deeper into streams and reading or writing data from files, you must first understand the difference between the character streams and byte streams, which is essential for understanding the rest of the chapter.

229

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