Java Reference
In-Depth Information
end-of-file indication occurs as an exception. In others, the indication is a return value
from a method invoked on a stream-processing object.
0123456789 .
...
n-1
end-of-file marker
Fig. 15.1 | Java's view of a file of n bytes.
Byte-Based and Character-Based Streams
File streams can be used to input and output data as bytes or characters.
Byte-based streams output and input data in its binary format—a char is two
bytes, an int is four bytes, a double is eight bytes, etc.
Character-based streams output and input data as a sequence of characters in
which every character is two bytes—the number of bytes for a given value de-
pends on the number of characters in that value. For example, the value
2000000000 requires 20 bytes (10 characters at two bytes per character) but the
value 7 requires only two bytes (1 character at two bytes per character).
Files created using byte-based streams are referred to as binary files , while files created us-
ing character-based streams are referred to as text files . Text files can be read by text edi-
tors, while binary files are read by programs that understand the file's specific content and
its ordering. A numeric value in a binary file can be used in calculations, whereas the char-
acter 5 is simply a character that can be used in a string of text, as in "Sarah Miller is 15
years old" .
Standard Input, Standard Output and Standard Error Streams
A Java program opens a file by creating an object and associating a stream of bytes or char-
acters with it. The object's constructor interacts with the operating system to open the file.
Java can also associate streams with different devices. When a Java program begins execut-
ing, it creates three stream objects that are associated with devices— System.in , Sys-
tem.out and System.err . The System.in (standard input stream) object normally enables
a program to input bytes from the keyboard. Object System.out (the standard output
stream object) normally enables a program to output character data to the screen. Object
System.err (the standard error stream object) normally enables a program to output char-
acter-based error messages to the screen. Each stream can be redirected . For System.in ,
this capability enables the program to read bytes from a different source. For System.out
and System.err , it enables the output to be sent to a different location, such as a file on
disk. Class System provides methods setIn , setOut and setErr to redirected the standard
input, output and error streams, respectively.
The java.io and java.nio Packages
Java programs perform stream-based processing with classes and interfaces from package
java.io and the subpackages of java.nio —Java's New I/O APIs that were first intro-
duced in Java SE 6 and that have been enhanced since. There are also other packages
throughout the Java APIs containing classes and interfaces based on those in the java.io
and java.nio packages.
 
Search WWH ::




Custom Search