Object-Oriented Programming with Java · Lecture Notes
Chapter 8: Input and Output
A program's variables live in memory and vanish when the program ends. Everything that has to last, such as measurement logs, configuration files, images, and student lists, is kept somewhere outside the program: on a disk, across a network, or on a device. A program's exchange of data with this outside world is called input and output (I/O). Java builds all of it on a single idea: data is a stream that flows in order from a source to a destination. These notes first introduce the stream concept and the standard streams of the keyboard and the screen. They then go down to the bytes inside files: the difference between text and binary files, character encodings, and how many bytes a number occupies in a file. The following sections cover the File class, the classes for reading and writing text, buffering, the other byte streams, and the ways of copying a file. The last sections treat random access, object serialization, and NIO, Java's library built on buffers and channels.
Learning outcomes
- Explain streams
- Describe input and output streams and the
System.in,System.out, andSystem.errstreams; read from the keyboard withScanner. - Tell text from binary
- Explain the difference between text and binary files and the ASCII, ISO-8859-9, and UTF-8 encodings; compute how many bytes a number occupies in a file.
- Read and write files
- Process text files with
File,Scanner,BufferedReader,PrintWriter, andFileWriter; close resources with try-with-resources. - Choose the right stream
- Distinguish byte streams (
InputStream/OutputStream) from character streams (Reader/Writer), and buffered streams from wrapper streams. - Copy and seek
- Copy at the byte, block, and line level; jump to a given position with
RandomAccessFile. - Store objects and use NIO
- Serialize objects (
Serializable,transient); explain what an NIO buffer, channel, and selector are for.
8.1Streams
A program takes data from the outside, processes it, and hands the result back. The outside can be a different place each time: the keyboard, the screen, a file on disk, a server on the network, or an array in memory. Learning a separate way of reading for each of these sources would be hard and unnecessary. Java treats them all through one abstraction: the stream.
8.1.1What is a stream?
A stream is a structure that carries data from a source to a destination in order, piece by piece. A stream through which data enters the program is an input stream, and a stream through which data leaves the program is an output stream. The pieces carried can be characters, numbers, or raw bytes.
A water pipe is a fitting analogy. Water that enters at one end of the pipe comes out at the other end in the same order, and whoever drinks the water does not care whether the far end is a tap or a tank. A stream works the same way. The program sees only its own end of the stream. The other end may be a keyboard, a file, or a network connection, and in every case the program calls the same read() and write() methods. The power of Java's I/O (input/output) library comes from this common interface. Figure 8.1 shows the structure.
InputStream and OutputStream; those of character streams are Reader and Writer.Two properties of streams matter throughout this chapter. The first is order: data read from a stream arrives in the order it was written, and an item cannot be skipped to reach the next one. For this reason a stream cannot jump straight to a record in the middle of a file; that requires random access. The second is direction: a stream is either an input stream or an output stream, never both. A program that wants to both read and write the same file opens two separate streams.
8.1.2Standard streams
The keyboard and the screen are the simplest I/O devices. Data handled through them is transient: what is typed at the keyboard and written to the screen is not stored, and it disappears when the program ends. It is also immediate: input arrives as the user types, and output appears on the screen as the program writes it. When a Java program starts, it receives three ready-made streams from the operating system. They are called the standard streams (Table 8.1).
| Stream | Java object | Type | Default endpoint |
|---|---|---|---|
| standard input | System.in | InputStream | keyboard |
| standard output | System.out | PrintStream | screen |
| standard error | System.err | PrintStream | screen |
System.in; the program writes to the screen through System.out and System.err. The numbers are the operating system's file descriptor numbers (0, 1, 2).System.out and System.err both write to the screen. So why are there two streams? The difference shows when output is redirected. If you type java Application > result.txt on the command line, the > sign redirects only standard output to the file result.txt. Whatever is written to System.err stays on the screen. This way error messages neither pollute the output file nor go unnoticed. A program's actual result goes to System.out; warnings and error messages go to System.err.
The type of System.in is InputStream, so it delivers raw bytes. When a user types 42 at the keyboard and presses Enter, three bytes enter the stream: '4', '2', and the line terminator. Converting these bytes into an int is left to the programmer. The class java.util.Scanner does that job.
8.1.3A first example: reading and writing
The following program uses all three standard streams. It reads a number from the keyboard, writes two lines to standard output, and writes one line to standard error.
import java.util.Scanner;
public class StreamDemo {
public static void main(String[] args) {
// Read from the input stream
Scanner scanner = new Scanner(System.in);
int userInput = scanner.nextInt();
// Write to the output stream
System.out.println("Hello, World!");
System.out.println("You entered: " + userInput);
System.err.println("This line went to stderr.");
}
}If the user types 42, the console shows the following lines (the first line is the input the user typed):
42
Hello, World!
You entered: 42
This line went to stderr.The program runs line by line as follows:
new Scanner(System.in)creates a scanner that reads the keyboard stream.Scanneris in thejava.utilpackage, which is why theimportline at the top of the file is required.scanner.nextInt()waits until the user types a number and presses Enter. This waiting is called blocking: the program stops at that line and continues once input arrives.System.out.printlnwrites a line to the output stream and ends the line.System.err.printlnwrites to the error stream. Most development environments show this line in red.
If the user types abc instead of a number, nextInt() cannot convert the text to a number and throws java.util.InputMismatchException. The program ends with an uncaught exception:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:947)
at java.base/java.util.Scanner.next(Scanner.java:1602)
at java.base/java.util.Scanner.nextInt(Scanner.java:2267)
at java.base/java.util.Scanner.nextInt(Scanner.java:2221)
at StreamDemo.main(StreamDemo.java:7)This is an unchecked exception; the compiler does not force you to catch it. In programs that cannot trust user input, check first with hasNextInt(), or catch the exception and ask the user again.
8.1.4Code trace: reading from the keyboard
The following program asks for the user's name and age and computes the age next year. It uses nextLine() to read the name and nextInt() to read the age. The two methods treat the line terminator differently, which causes one of the most common mistakes in this chapter; the trace makes the difference visible.
import java.util.Scanner;
public class ConsoleInput {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Name: ");
String name = keyboard.nextLine();
System.out.print("Age: ");
int age = keyboard.nextInt();
int nextYear = age + 1;
System.out.println("Hello " + name + "!");
System.out.println("Next year you'll be " + nextYear + ".");
keyboard.close();
}
}Suppose the user types Ayşe Yılmaz as the name and 19 as the age. Table 8.2 gives every step of the program. The line numbers refer to the lines of the code above.
| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 5: Scanner keyboard = new Scanner(System.in); | keyboard=Scanner(System.in) | — |
| 2 | 6: System.out.print("Name: "); | keyboard=Scanner(System.in) | Name: |
| 3 | 7: String name = keyboard.nextLine(); | name="Ayşe Yılmaz" | Ayşe Yılmaz |
| 4 | 8: System.out.print("Age: "); | name="Ayşe Yılmaz" | Age: |
| 5 | 9: int age = keyboard.nextInt(); | name="Ayşe Yılmaz", age=19 | 19 |
| 6 | 10: int nextYear = age + 1; | name="Ayşe Yılmaz", age=19, nextYear=20 | — |
| 7 | 11: System.out.println("Hello " + name + "!"); | name="Ayşe Yılmaz", age=19, nextYear=20 | Hello Ayşe Yılmaz! |
| 8 | 12: System.out.println("Next year you'll be " + nextYear + "."); | name="Ayşe Yılmaz", age=19, nextYear=20 | Next year you'll be 20. |
| 9 | 13: keyboard.close(); | name="Ayşe Yılmaz", age=19, nextYear=20 | — |
In the first step the Scanner object is attached to the System.in stream. Nothing has been read yet, and the keyboard buffer is empty. In the second step print (not println) writes the prompt Name: . Because print does not end the line, the user's answer is typed right next to the prompt.
The third step is the important one. The user types Ayşe Yılmaz and presses Enter. The keyboard buffer now holds Ayşe Yılmaz⏎. nextLine() takes everything up to the line terminator, spaces included, and also discards the terminator from the buffer. The variable name is assigned "Ayşe Yılmaz"; the line terminator is not part of this text.
In the fifth step the user types 19 and presses Enter. nextInt() skips leading whitespace, reads the digits, and converts them to the int value 19. It does not touch the line terminator: ⏎ stays in the buffer. This causes no trouble here, because no further read follows. In the later steps age is an ordinary int: 19 + 1 = 20. The output lines are built by string concatenation: "Next year you'll be " + 20 + ".".
nextLine() takes the whole line and discards the line terminator. (b) nextInt() takes the digits; the line terminator stays in the buffer.The keyboard.close() on the last line closes not just the scanner but also the System.in stream it wraps. A closed standard input cannot be reopened. Even if the program later creates a new Scanner(System.in), it cannot read from the keyboard. The small experiment below shows this: after the first scanner is closed, the second one throws NoSuchElementException even though a line is waiting in the input.
read: one
java.util.NoSuchElementException: No line foundFor this reason, the scanner that reads the keyboard is created once in a program and, if at all, closed only at the very end. Scanners that read files, on the other hand, should be closed as soon as the work is done; the file sections return to this difference.
8.1.5nextLine after nextInt
The effect of the leftover line terminator shows up when the order is reversed. Suppose the age is read first and the name second:
import java.util.Scanner;
public class LineAfterInt {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Age: ");
int age = keyboard.nextInt();
System.out.print("Name: ");
String name = keyboard.nextLine();
System.out.println("[" + name + "] " + age);
}
}The user types 19 and presses Enter. nextInt() reads 19 and leaves the line terminator in the buffer. Then nextLine() is called. This method asks for the text up to the next line terminator. A line terminator is already waiting in the buffer, and the text in front of it is empty. nextLine() returns the empty string without waiting at all. The program ends before the user gets a chance to type a name:
Age: Name: [] 19Reading text with nextLine() right after a call to nextInt(), nextDouble(), or next(). The first nextLine() reads the line terminator left over from the previous line and returns an empty string. There are two fixes: insert an extra keyboard.nextLine(); that discards the terminator, or read the number as a line too and convert it: int age = Integer.parseInt(keyboard.nextLine());.
The second fix is usually cleaner. Because every read consumes a whole line, nothing is left in the buffer. If the user types extra spaces next to the number, parseInt fails; in that case use keyboard.nextLine().trim().
8.2Files and encodings
Exchange through the keyboard and the screen is transient. Lasting data needs a file. This section explains what a file really is, how text files differ from binary files, and how characters are converted into bytes. This knowledge decides which stream class to choose in the later sections.
8.2.1A file: a sequence of bytes on disk
A file stores data permanently on disk. The data stays in place even when the program ends or the computer restarts. Variables in RAM, by contrast, vanish with the program. The data in every file ultimately consists of 0s and 1s, that is, of a sequence of bytes. What distinguishes one file from another is how these bytes are interpreted.
In a text file, bytes are converted into letters according to a character encoding; a person can read the file with a text editor. In a binary file, the bytes are data such as numbers, pixels, audio samples, or machine instructions; only a program that knows the format of the file can make sense of them.
To see the bytes of a file, you use a hexadecimal (hex) editor. This tool shows each byte as two hexadecimal digits. A file file.txt containing Merhaba, dünya! looks like this in a hex editor:
0000 4D 65 72 68 61 62 61 2C Merhaba,
0008 20 64 C3 BC 6E 79 61 21 d..nya!The left column is the position of the first byte on each line: 0000 and 0008. The middle holds the hexadecimal value of each byte, and the right the ASCII equivalent. The first byte is 4D: 4 · 16 + 13 = 77, which is the capital letter M in ASCII. The text has 15 characters, but the file takes 16 bytes. The difference comes from the letter ü: in UTF-8, ü is two bytes, C3 BC. The two dots in the right column show that these two bytes have no ASCII equivalent. If the file is produced with Java and its bytes are printed, the same 16 values appear:
16 bytes: 4D 65 72 68 61 62 61 2C 20 64 C3 BC 6E 79 61 21
1 byte: 7F
1382 bytes: CA FE BA BE 00 00 00 41 00 5C 0A 00 02 00 03 07 00 04 0C 00 05 00 06 01 00 10 6A 61 76 61 2F 6C
·······A·\················java/lang/Object···<init>···()V······java/io/FileWriter······file.txt·············(Ljava/lang
major = 65The first line of the output gives the bytes of this file, and the second line gives the bytes of the file data.dat. The remaining lines show the beginning of a .class file; these are explained when binary files are discussed.
8.2.2The file-processing cycle
Whatever language is used, working with a file goes through the same steps. Figure 8.4 shows the steps, and Table 8.3 gives the Java counterpart of each.
| Step | What happens | In Java |
|---|---|---|
| Create | A new, empty file appears on disk. | file.createNewFile(); opening a file for writing also creates it |
| Open | A stream is attached to an existing file. | new FileInputStream(name), new FileReader(name), new Scanner(file) |
| Write | Data is transferred to the file. | write(), print(), println() |
| Read | Data is brought from the file into the program. | read(), readLine(), nextLine() |
| Close | Data left in the buffer is written to disk, and the operating system releases the resource. | close() or try-with-resources |
The last step is the one most often forgotten. A file that is not closed causes two problems. The first is data loss: some of the bytes written wait in a buffer in memory and may never reach the disk unless the file is closed. The second is a resource leak: the operating system allocates a file handle for every open file, and the number of files a process can keep open at once is limited. A long-running program that never closes its files eventually cannot open new ones. On Windows, a file left open also cannot be deleted or moved.
8.2.3A first file program
The following program writes one sentence to a text file and a single byte to a binary file. It then reads the byte back from the binary file and prints the size of the text file.
import java.io.*;
public class FirstFile {
public static void main(String[] args) throws IOException {
// Write to a text file
FileWriter writer = new FileWriter("file.txt");
writer.write("Merhaba, dünya!");
writer.close();
// Write one byte to a binary file
FileOutputStream out = new FileOutputStream("data.dat");
out.write(127);
out.close();
// Read from the binary file
FileInputStream stream = new FileInputStream("data.dat");
int b = stream.read();
stream.close();
System.out.println("Byte read: " + b);
File text = new File("file.txt");
System.out.println("file.txt: " + text.length() + " bytes");
}
}Byte read: 127
file.txt: 16 bytesAfter the program has run, the contents of file.txt are:
Merhaba, dünya!The program uses three different stream classes:
FileWriterwrites text. It converts the characters it is given into bytes with a character encoding and sends them to the file. Since Java 18 the default encoding is UTF-8; that is whyübecomes two bytes and the 15-character text takes 16 bytes.FileOutputStreamwrites raw bytes. The callwrite(127)puts a single byte in the file:7Fin hexadecimal,0111 1111in binary. No character conversion takes place.FileInputStreamreads raw bytes.read()returns a byte as anintbetween 0 and 255. If there is no byte left to read, it returns −1; this detail matters in the section on copying.
The throws IOException in the header of main declares that file operations can throw a checked exception. The file may not exist, the disk may be full, or permission may be missing. The compiler requires these cases to be handled: either caught with try-catch or declared with throws in the method header. These short examples choose the second way. In real programs it is better to catch the exception so that the error message can be given to the user in an understandable form.
8.2.4Text files and character encodings
Text files contain printable characters: letters, digits, punctuation marks, spaces, and line terminators. They can be opened and edited with text editors such as Notepad or VS Code. Source code (.java, .c), .txt, .csv, and .html files are text files.
A computer cannot store letters, only numbers. So every character is assigned a number. The rule of this mapping is called a character encoding.
A character encoding, also called a character set, is the rule that determines with which number, that is, with which byte or bytes, each character is stored. The programs that write and read a text file must use the same encoding.
Many encodings have appeared over the course of history. The four met in this course are summarized in Table 8.4.
| Encoding | Per character | Coverage |
|---|---|---|
| ASCII | 7 bits (1 byte) | 128 characters: English letters, digits, punctuation, and control characters. |
| ISO-8859-1 (Latin-1) | 1 byte | 256 characters, Western European languages. It has é, ü, ö, ç; it does not have ş, ğ, ı. |
| ISO-8859-9 (Latin-5) | 1 byte | The Turkish variant of Latin-1. Six letters of Latin-1 are replaced by ğ Ğ ı İ ş Ş. |
| UTF-8 | 1–4 bytes | The universal encoding of Unicode; all the world's languages. The default encoding of the web and, since Java 18, of Java. |
UTF-8 is a variable-length encoding. The 128 ASCII characters are written in UTF-8 with the same single byte, so an ASCII file containing only English letters is also a valid UTF-8 file. Turkish letters and other Latin letters take two bytes, symbols such as the euro sign € take three, and emoji take four. The experiment below measures these numbers with the getBytes method:
32 characters, UTF-8 41, ISO-8859-9 32, UTF-16BE 64
IÅ<9f>ık, Å<9f>imÅ<9f>ek, çiÄ<9f>, öÄ<9f>renci, Ã<9c>nye
ş: ASCII 3F, UTF-8 C5 9F, ISO-8859-9 FE, cp1254 FE
þimdi
şimdi
Çağrı UTF-8: 8, ISO-8859-9: 5, UTF-16BE: 10
€ UTF-8: 3, 😀 UTF-8: 4, 😀 length(): 2
default: UTF-8 / native.encoding=Cp1254
4D 65 72 68 61 62 61 2C 20 64 C3 BC 6E 79 61 21The first line shows that a 32-character Turkish sentence takes 41 bytes in UTF-8, 32 in ISO-8859-9, and 64 in UTF-16. The sentence has nine Turkish letters that take two bytes each: 32 + 9 = 41. The second line is the same bytes decoded with the wrong encoding; this garbling is discussed in detail in the section on specifying the encoding. The ş line gives the bytes of one letter in four encodings. ASCII has no ş; Java writes a question mark (3F) in its place. The “Çağrı” line gives an interesting detail too: "Çağrı" has five characters but takes 8 bytes in UTF-8. Ç, ğ, and ı take two bytes each, and a and r one each: 2 + 1 + 2 + 1 + 2 = 8. The same text is 5 bytes in ISO-8859-9 and 10 bytes in UTF-16. For 😀, length() returns 2. Java's char type is 16 bits wide, and characters with code points above 65,535 are represented by two char values. So the length of a string does not always equal either the number of characters or the number of bytes.
The "default" line in the output deserves attention too. In Java 18 and later, the default encoding is UTF-8 regardless of the operating system. The operating system's own encoding is stored in the native.encoding property; on Turkish Windows this is Windows-1254 (Cp1254). In Java 17 and earlier, the default encoding was directly this operating system setting. The same program could write different bytes on Windows and on Linux.
8.2.5Binary files
Binary files store bytes not as characters but in a format chosen by the program: numbers, pixels, audio samples, machine code. These bytes are meaningful only to a program that knows the format; a person cannot read them directly. Executable files (.exe, Java's .class files), images (.png, .jpg), music (.mp3), video (.mp4), and data files (.dat) are binary files. The advantages of binary files are that they are smaller and faster to process: a number does not have to be converted to text and back.
The first 32 bytes of FirstFile.class, produced by compiling the previous program, look like this in a hex editor:
0000 CA FE BA BE 00 00 00 41 .......A
0008 00 5C 0A 00 02 00 03 07 .\......
0010 00 04 0C 00 05 00 06 01 ........
0018 00 10 6A 61 76 61 2F 6C ..java/lEvery .class file begins with the bytes CA FE BA BE. These four bytes are called the magic number; the JVM recognizes from it that the file really is a class file. The next four bytes are version information. 00 41 = 65 is the class-file version of Java 21; this number was also read from a file compiled with JDK 21, using Java itself (major = 65 in the earlier output). The constant pool follows. Some readable pieces are visible as well: class names such as java/lang/Object are stored in the file as text. When the same file is opened in Notepad, a meaningless string of characters appears:
Êþº¾···A·\················java/lang/Object···<init>···()V······java/io/FileWriter······file.txt·············(Notepad tries to decode the bytes with a text encoding. CA, FE, BA, and BE are the characters Ê, þ, º, and ¾ in Latin-1. Bytes that cannot be printed appear as dots or spaces. Opening a binary file in a text editor and saving it can corrupt it: the editor may change some bytes or convert the line terminators.
8.2.6Extended ASCII and Turkish characters
ASCII is 7 bits and covers 128 characters. A byte, however, is 8 bits. The one remaining bit makes room for 128 new characters.
Extended ASCII is the general name for encodings that use all 8 bits to represent 28 = 256 characters. Codes 0–127 are the standard ASCII characters and are the same in every table. Codes 128–255 are reserved for special characters, symbols, and national letters.
There is no single "extended ASCII". Which characters the upper half holds varies with the code page. Two code pages are used for Turkish: ISO-8859-9 (Latin-5) and Windows-1254. They use the same bytes for the Turkish letters. Table 8.5 shows the meaning of the same bytes in Latin-1 and Latin-5 side by side.
| Byte | D0 | DD | DE | F0 | FD | FE | FC | E7 |
|---|---|---|---|---|---|---|---|---|
| ISO-8859-1 | Ð | Ý | Þ | ð | ý | þ | ü | ç |
| ISO-8859-9 | Ğ | İ | Ş | ğ | ı | ş | ü | ç |
FC and E7 are ü and ç in both tables; these letters exist in Western European languages too. The first six bytes, however, change from table to table. The same byte FE is ş in one table and the Icelandic letter þ in the other. When a Turkish file is opened with the wrong code page, garbled text such as “þimdi” instead of “şimdi” appears (Figure 8.5). The þimdi and şimdi lines in the earlier output were obtained from the same five bytes with the two code pages.
FE is ş in ISO-8859-9 and þ in ISO-8859-1. Opening a file with the wrong code page garbles the text.The lasting solution to this problem is Unicode, which collects all languages in a single table, and its byte encoding UTF-8. In UTF-8 each character has exactly one byte sequence; the reader does not have to guess which code page to choose. UTF-8 is the choice for every text file written today.
8.2.7Writing 127 to a file
How a number is stored in a file depends on its data type, its purpose, and the file format. The number 127 can be written in two fundamentally different ways.
- Written as text, the number is first converted into characters:
"127". Each digit takes one ASCII byte. A point that is often confused matters here: the code of the character'1'is not 1 but 49.'2'is 50 and'7'is 55. The file holds the bytes31 32 37. - Written as binary, the binary value of the number,
0111 1111, is written directly into as many bytes as the type is wide: 1 byte forbyte, 2 forshort, and 4 forint. For numeric data this way is more efficient.
The following program really writes these five representations to files and measures the file sizes. It uses OutputStreamWriter to write text and DataOutputStream to write binary. For brevity, the lines import java.io.*; and import java.nio.charset.*; are not shown.
public class Number127 {
static void writeText(String name, Charset cs) throws IOException {
Writer w = new OutputStreamWriter(new FileOutputStream(name), cs);
w.write(String.valueOf(127)); // "127": 3 chars
w.close();
}
static void writeBinary(String name, int size) throws IOException {
FileOutputStream fos = new FileOutputStream(name);
DataOutputStream d = new DataOutputStream(fos);
if (size == 1) d.writeByte(127); // 01111111
else if (size == 2) d.writeShort(127); // 00000000 01111111
else d.writeInt(127); // 4 bytes
d.close();
}
public static void main(String[] args) throws IOException {
writeText("text.txt", StandardCharsets.US_ASCII);
writeText("text16.txt", StandardCharsets.UTF_16BE);
writeBinary("b.dat", 1); writeBinary("s.dat", 2); writeBinary("i.dat", 4);
String[] names = {"text.txt", "text16.txt",
"b.dat", "s.dat", "i.dat"};
for (String name : names)
System.out.println(name + ": " + new File(name).length());
}
}text.txt: 3
text16.txt: 6
b.dat: 1
s.dat: 2
i.dat: 4The writeText method wraps a FileOutputStream in an OutputStreamWriter. OutputStreamWriter is the bridge class that converts characters into bytes with the encoding it is given. With ASCII, "127" takes three bytes. UTF_16BE writes each character with two bytes and takes 6 bytes. The BE (big-endian) in the name of this encoding fixes the byte order, so no byte order mark (BOM) is written at the start of the file. Had the UTF_16 encoding with a byte order mark been used, two bytes FE FF would have been added at the start and the file would have taken 8 bytes.
The writeBinary method uses DataOutputStream. This class writes primitive types in their fixed-size binary representations: writeByte 1, writeShort 2, and writeInt 4 bytes. The bytes are written with the most significant byte first. The actual contents of the files confirm the measurement:
text.txt: 3
text16.txt: 6
b.dat: 1
s.dat: 2
i.dat: 4
text.txt -> 31 32 37
text16.txt -> 00 31 00 32 00 37
b.dat -> 7F
s.dat -> 00 7F
i.dat -> 00 00 00 7F
UTF_16 (with BOM): 8
two ints: 8
7 2000000000
wrong order/type: 0 7
EOFException: nullThe last lines of the output show two important rules about DataInputStream. Values in a binary file are read back correctly only in the order and with the type in which they were written. If a file with two int values is read with two readShort() calls, 0 and 7 come back; that is, the four bytes of the first int are split into two pieces. If readInt() is called when the file has no more data, an EOFException (end of file) is thrown. A text file explains its own format to a person; for a binary file, the program that writes it and the program that reads it must know the format in advance.
8.2.8Text or binary?
Table 8.6 compares the five representations of the number 127 by size.
| How was 127 written? | Bytes | Size |
|---|---|---|
| ASCII / UTF-8 text file | 31 32 37 | 3 bytes |
| UTF-16 text file (no BOM) | 00 31 00 32 00 37 | 6 bytes |
Binary, byte | 7F | 1 byte |
Binary, short | 00 7F | 2 bytes |
Binary, int | 00 00 00 7F | 4 bytes |
writeInt.In the table the binary representation always looks smaller, but that is true only for 127. In binary, the size depends on the type: an int is always 4 bytes, whether its value is 7 or 2,000,000,000. In text, the size depends on the number of digits: 7 takes one byte, while 2,000,000,000 takes ten. For small numbers text can be shorter; for large numbers binary clearly wins. Binary reading is also fast because it does not have to parse the number.
The choice depends on the purpose:
- Text is for data that people will read. It opens in every editor, moves easily between platforms, and can be repaired by eye when it is damaged. Log files, configuration files, and CSV tables are text.
- Binary is for storing numeric data efficiently. It is smaller and faster, but you must know the format of the program that wrote it. Image, audio, and database files are binary.
Java has clear tools for these two ways. DataOutputStream writes primitive types in binary (writeByte, writeShort, writeInt, and so on). DataInputStream reads them back in the same order. OutputStreamWriter converts characters into bytes with a given encoding.
8.3The file system: the File class
Before reading the contents of a file, you often ask questions about the file itself. Does the file exist? Is it a file or a directory? How large is it? Is it readable? The java.io.File class answers these questions.
8.3.1A File is a path
A File object represents a path on disk: the name and location of a file or directory. File does not read or write the contents of a file; that is the job of streams. File only accesses the file system to answer questions about the path and to perform operations such as creating, deleting, and listing files or directories.
The most important consequence of this distinction is that new File("sample.txt") creates nothing on disk. The constructor merely stores the path in an object. The object is created even if the file is not on disk, and no exception is thrown. For a nonexistent file, exists() returns false and length() returns 0. The exception for a missing file comes only when a stream is opened to read it; for example, new FileReader(f) throws FileNotFoundException.
false 0 missing.txt false
mkdir: false, mkdirs: true
second createNewFile: false
non-empty directory delete: false
lastModified(missing) = 0
1 a/bThe first line of this output gives the values of exists(), length(), getName(), and isFile() for the nonexistent missing.txt. The remaining lines show the subtle points of the methods explained below. Table 8.7 summarizes the commonly used methods.
| Method | Returns |
|---|---|
exists() | whether the path exists on disk (boolean) |
isFile() / isDirectory() | whether it is a file / a directory |
canRead(), canWrite(), canExecute() | read, write, and execute permission |
createNewFile() | whether the file was created (false if it already exists) |
mkdir() / mkdirs() | whether the directory was created (mkdirs also creates intermediate directories) |
delete() | whether it was deleted (a non-empty directory is not deleted) |
list() / listFiles() | the contents of a directory: String[] / File[] |
length() | size in bytes (long) |
lastModified() | time of last modification, in milliseconds since 1 January 1970 |
getName(), getAbsolutePath() | the name, the full path |
Most of these methods do not throw an exception on failure; they return false. mkdir() fails if the intermediate directories do not exist; in the output above, for a/b/c, mkdir returns false while mkdirs returns true. createNewFile() returns false if the file already exists and leaves the existing file alone. delete() does not delete a non-empty directory and again returns false. The lastModified() of a nonexistent file is 0. Consequently, the return values of these methods must be checked. If the value is ignored, the operation fails silently and the error is noticed only much later.
8.3.2File and directory operations
The following program creates a directory with an empty file inside it, queries the file's properties, and then deletes everything.
public class FileInfo {
public static void main(String[] args) throws IOException {
File dir = new File("sample");
File file = new File("sample/file.txt");
System.out.println("exists: " + file.exists());
System.out.println("mkdir: " + dir.mkdir());
System.out.println("created: " + file.createNewFile());
System.out.println("isFile: " + file.isFile());
System.out.println("isDir: " + file.isDirectory());
System.out.println("readable: " + file.canRead());
System.out.println("writable: " + file.canWrite());
System.out.println("size: " + file.length());
String[] items = dir.list();
System.out.println("in dir: " + items.length + " item(s)");
long time = file.lastModified();
System.out.println("time > 0: " + (time > 0));
System.out.println("deleted: " + file.delete());
System.out.println("exists: " + file.exists());
dir.delete();
}
}exists: false
mkdir: true
created: true
isFile: true
isDir: false
readable: true
writable: true
size: 0
in dir: 1 item(s)
time > 0: true
deleted: true
exists: falseOn the first line the file does not exist yet. mkdir() creates the sample directory and createNewFile() creates the empty file inside it; both return true. Because the file was just created, its size is 0. dir.list() returns the names in the directory as an array; the length of the array is 1. The value of lastModified() differs every time the program runs, so the program prints only whether it is greater than zero. Finally the file is deleted and exists() is false again. The last statement deletes the directory; since the directory is now empty, the deletion succeeds.
Both paths in the program are relative paths: "sample/file.txt" is interpreted relative to the directory the program runs in. In a development environment this is usually the root directory of the project. getAbsolutePath() converts a relative path into a full path and shows where the file is really being looked for. When you get a "file not found" error, this is the first place to look.
The path separator is the backslash (\) on Windows and the slash (/) on Linux and macOS. Java accepts / on Windows too, so "sample/file.txt" works on every system. The system's own separator is stored in the constant File.separator. If backslashes are to be used in Windows paths, they must be written twice in a Java string: "C:\\courses\\notes.txt". A single backslash starts an escape sequence. "C:\courses" does not compile, because \c is not a valid escape sequence:
Main.java:5: error: illegal escape character
java.io.File f = new java.io.File("C:\courses\notes.txt");
^
1 errorThe sneakier case is when the escape sequence is valid. "C:\notes.txt" compiles, because \n is a line terminator. The path silently turns into C:, a line terminator, and otes.txt:
COMPILED; ran: C:
otes.txt8.4Reading and writing text
Most file work is done with text files. This section explains the ways of reading and writing text, the class structure behind them, and how to close resources safely.
8.4.1Reading a file with Scanner
Scanner can read not only the keyboard but also a file or a String. To change the source, a File object is passed to the constructor instead of System.in. The reading methods are the same. The following program reads a file line by line and prints it to the screen. The required imports are java.io.File, java.io.FileNotFoundException, and java.util.Scanner.
public class ScannerFile {
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(new File("sample.txt"));
// Read the file and print it
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
} finally {
if (scanner != null)
scanner.close();
}
}
}Let sample.txt contain three lines: Java, Input Output, and Streams. The program prints them as they are:
Java
Input Output
StreamsThree points of the program deserve explanation:
- A checked exception.
new Scanner(File)throwsFileNotFoundExceptionif the file does not exist. This is a checked exception: it is either caught or declared in the method header. The program catches it and writes a message to the error stream. - The loop.
hasNextLine()asks whether there is a line to read, andnextLine()takes the line. At the end of the filehasNextLine()returnsfalseand the loop ends. finallyand thenullcheck. If the file cannot be opened, the variablescannerstaysnull. Thefinallyblock runs in every case; without the check,close()would be called through anullreference.
The last point is more important than it looks. If the line if (scanner != null) is removed and the program tries to open a nonexistent file, it first prints the "File not found" message and then crashes in finally:
File not found: missing.txt (The system cannot find the file specified)
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Scanner.close()" because "<local1>" is null
at NoNullCheck.main(NoNullCheck.java:12)This pattern is both long and error-prone. The try-with-resources statement, introduced in Java 7, does the same job briefly and safely. Scanner implements the AutoCloseable interface, so it can be opened in the parentheses of try and is closed automatically when the block ends. Neither finally nor the null check is needed:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TryWithResources {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File("sample.txt"))) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
}
Scanner s = new Scanner("3 4,5 apple\nsecond line");
System.out.println(s.nextInt() + " | " + s.next() + " | " + s.next() + " | " + s.nextLine() + " | " + s.nextLine());
}
}Java
Input Output
Streams
3 | 4,5 | apple | | second lineThe two lines at the end of the program show that Scanner can also read a String. nextInt() takes the 3, and the two next() calls take the words 4,5 and apple, each up to the next space. The first nextLine() that follows returns the rest of the line, which is the empty string; the second nextLine() returns the actual second line. This is exactly the nextInt–nextLine trap seen with the keyboard.
8.4.2Code trace: try-with-resources and closing order
try-with-resources is the form of try that automatically closes the resources opened in the parentheses after the try keyword when the block ends. Only objects that implement the AutoCloseable interface can be opened in the parentheses. Resources are closed in the reverse of the order in which they were opened; closing happens whether the block ends normally or with an exception.
To see the closing order, we write a small resource class that prints a message when it is opened and when it is closed. Res implements the AutoCloseable interface; its only method is close().
class Res implements AutoCloseable {
String name;
Res(String name) { this.name = name; System.out.println(name + " opened"); }
public void close() { System.out.println(name + " closed"); }
}
public class CloseOrder {
public static void main(String[] args) {
try (Res a = new Res("A"); Res b = new Res("B")) {
System.out.println("block running");
throw new IllegalStateException("error!");
} catch (IllegalStateException e) {
System.out.println("caught: " + e.getMessage());
} finally { System.out.println("finally"); }
}
}A opened
B opened
block running
B closed
A closed
caught: error!
finallyTable 8.8 gives the eight steps of the program.
| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 8: try (Res a = new Res("A"); Res b = new Res("B")) { | a=Res("A") | A opened |
| 2 | 8: try (Res a = new Res("A"); Res b = new Res("B")) { | a=Res("A"), b=Res("B") | B opened |
| 3 | 9: System.out.println("block running"); | a=Res("A"), b=Res("B") | block running |
| 4 | 10: throw new IllegalStateException("error!"); | a=Res("A"), b=Res("B") | — |
| 5 | 4: public void close() { System.out.println(name + " closed"); } | this.name="B" | B closed |
| 6 | 4: public void close() { System.out.println(name + " closed"); } | this.name="A" | A closed |
| 7 | 11: } catch (IllegalStateException e) {12: System.out.println("caught: " + e.getMessage()); | e=IllegalStateException("error!") | caught: error! |
| 8 | 13: } finally { System.out.println("finally"); } | — | finally |
In the first two steps the resources in the parentheses are created in order from left to right: first a, then b. In the third step the body of the block runs; both resources are open. In the fourth step the body throws an exception.
The fifth and sixth steps are the heart of this construct. Although an exception has been thrown, control does not pass to catch immediately. First the resources are closed, and they are closed in reverse order: b, opened last, closes first, then a. The reverse order has a reason. A resource opened later may depend on an earlier one; for example, a writer may wrap a file stream. Closing the outer one first lets it flush its buffer while the inner stream is still open.
In the seventh step catch catches the exception. At this point a and b are out of scope: variables declared in the parentheses are visible only inside the try block. A use such as a.close() inside catch or after the block does not compile. In the eighth step finally runs. The full order is: open A, open B, body, close B, close A, catch, finally.
b, opened last, closes. (c) After both resources are closed, catch catches the exception.8.4.3The java.io library
The java.io package offers a powerful and flexible toolkit for input and output. It is used in a wide range of areas, from file operations to network programming. The package provides flexibility along three axes:
- Input and output: it receives data from sources such as files, networks, and memory, and sends data to them.
- Binary and text: it supports both byte-based (binary) and character-based (text) operations.
- Sequential and random: it reaches the data in a file both in order and by jumping to a chosen position.
The elements of the package fall into three groups (Table 8.9).
| Kind of element | Examples | Purpose |
|---|---|---|
| Classes | File | operations on files and directories (paths) |
InputStream, OutputStream | basic byte input and output | |
Reader, Writer | text (character) input and output | |
| Interfaces | Closeable, AutoCloseable | releasing a resource: close() |
Flushable | emptying the buffer: flush() | |
| Exceptions | IOException | the superclass of I/O errors |
FileNotFoundException, EOFException | file not found / unexpected end of file |
8.4.4Byte streams and character streams
The streams in java.io fall into two large families. The distinction is made by the unit the stream carries.
Byte streams process data as 8-bit bytes; their superclasses are InputStream and OutputStream. Character streams process data as 16-bit Unicode char values; their superclasses are Reader and Writer. Character streams convert bytes into characters, and characters into bytes, with a character encoding.
Byte streams work with binary data such as images, audio, video, and .class files. read() returns a byte between 0 and 255 and does not care what the byte means. Character streams are designed for text-based data. Because they decode the encoding, they handle different languages and alphabets correctly. Table 8.10 compares the two families.
| Byte stream | Character stream | |
|---|---|---|
| Unit read | byte (8 bits) | char (16 bits) |
| Superclasses | InputStream, OutputStream | Reader, Writer |
| File classes | FileInputStream, FileOutputStream | FileReader, FileWriter |
| Buffered | BufferedInputStream, BufferedOutputStream | BufferedReader, BufferedWriter |
| Use | any kind of file, copying | text files only |
Reading text with a byte stream is possible but hard. The following experiment reads the word Işık byte by byte and converts each byte to a character with (char):
IÅık (6 char)A four-letter word comes out as six "characters". ş and ı are two bytes each in UTF-8, and a byte stream delivers these bytes separately. Converting every byte to a char on its own produces wrong letters. A character stream, by contrast, decodes the two bytes together and returns the right letter.
There are bridge classes between the two families. InputStreamReader turns a byte stream into a character stream, and OutputStreamWriter turns characters into a byte stream. The encoding is applied in these bridges. The writeText method that wrote a number in UTF-16 used this bridge.
8.4.5Class hierarchies
Each of the two families consists of classes derived from an abstract superclass. Figure 8.9 shows the byte streams and Figure 8.10 the character streams.
System.out is a PrintStream.InputStream and OutputStream at the top of the hierarchy are abstract classes, so no objects are created from them directly. The subclasses take on two kinds of work. Some connect to a data source: FileInputStream connects to a file, ByteArrayInputStream to an array in memory, and PipedInputStream to a pipe. The others derive from FilterInputStream and FilterOutputStream. These do not connect to a source on their own; they wrap another stream and add a new capability to it. BufferedInputStream adds a buffer, and DataInputStream adds the ability to read primitive types.
FileReader is an InputStreamReader; FileWriter likewise derives from OutputStreamWriter.Character streams follow the same pattern. The relationship that stands out here is the position of FileReader. A FileReader is really an InputStreamReader: inside, it opens a FileInputStream and converts the bytes coming from it into characters with the chosen encoding. FileWriter likewise derives from OutputStreamWriter. So underneath every character stream there is, in the end, a byte stream. A disk only knows bytes.
8.4.6Wrapper streams
Every class in Java's I/O library does one job well. FileReader reads characters from a file but does not recognize lines. BufferedReader reads lines but cannot connect to a file. The capabilities you need are combined by nesting streams inside one another.
A wrapper stream (also called a decorator) is a stream that takes another stream in its constructor and adds a new capability to it, such as buffering, line reading, or reading of primitive types. The wrapper's methods do part of the work themselves and pass the rest on to the inner stream. This arrangement is known as the Decorator design pattern.
BufferedReader reader = new BufferedReader(new FileReader("sample.txt"));
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("file2.txt")));The first line has two layers: FileReader opens the file and converts bytes to characters; BufferedReader wraps it and adds a buffer and readLine(). The second line has three layers: FileWriter converts characters to bytes and writes them to the file, BufferedWriter adds a buffer, and PrintWriter adds convenient writing methods such as print, println, and printf (Figure 8.11).
You can think of a garden hose: first a filter and then a spray nozzle are attached to the end of the hose. The water, which is the data, passes through all of them in turn. Each part does its own job, and the parts can be combined in any order you like. To add a capability, you do not need to write a new class; you combine the existing wrappers.
Wrapping has two rules. The first: closing the outermost stream closes all the inner ones. writer.close() first flushes its own buffer, then the buffer of the BufferedWriter, and finally closes the FileWriter and the file. The inner streams do not have to be closed separately. The second: a wrapper interprets the data but does not validate it. If a text file is wrapped in a DataInputStream and readInt() is called, the first four bytes, the codes of the letters J, a, v, a, are read as the integer 1,247,901,281. The stream raises no error; the wrong wrapper produces a wrong but valid-looking result.
8.4.7Code trace: BufferedReader
The most common way to read a text file line by line is the readLine() method of BufferedReader. The method returns the next line without its line terminator; when the file ends, it returns null.
import java.io.*;
public class ReadLines {
public static void main(String[] args) {
File file = new File("sample.txt");
try (BufferedReader reader =
new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Read error: " + e.getMessage());
e.printStackTrace();
}
}
}The expression (line = reader.readLine()) != null in the loop condition is a common pattern in Java I/O code. First the assignment in the parentheses is performed: the line read is stored in the variable line. The value of an assignment expression is the assigned value itself. This value is compared with null. So reading and the end-of-file check happen on one line. The outer parentheses are required. Without them != would run first and a boolean value would be assigned to a String variable; the code would not compile. When the file contains the lines Java, Input Output, and Streams, the trace is as in Table 8.11.
| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 5: File file = new File("sample.txt"); | file="sample.txt" | — |
| 2 | 6: try (BufferedReader reader =7: new BufferedReader(new FileReader(file))) { | reader=BufferedReader | — |
| 3 | 9: while ((line = reader.readLine()) != null) { | line="Java" | — |
| 4 | 10: System.out.println(line); | line="Java" | Java |
| 5 | 9: while ((line = reader.readLine()) != null) { | line="Input Output" | — |
| 6 | 10: System.out.println(line); | line="Input Output" | Input Output |
| 7 | 9: while ((line = reader.readLine()) != null) { | line="Streams" | — |
| 8 | 10: System.out.println(line); | line="Streams" | Streams |
| 9 | 9: while ((line = reader.readLine()) != null) { | line=null | — |
| 10 | 12: } catch (IOException e) { | — | — |
In the first step only a File object is created; the file has not been opened yet. In the second step FileReader opens the file and BufferedReader wraps it. The read position is at the start of the file. In the third step the first call to readLine() returns "Java". By this time BufferedReader has read a large chunk of the file in one go and put it in its buffer; for a small file the whole file fits into the buffer. The following lines are served from the buffer without going to disk.
readLine() trace. (a) The first line is read and its line terminator is discarded. (b) At the end of the file readLine() returns null and the loop ends.In the ninth step the file ends and readLine() returns null. The loop terminates. In the tenth step the try block ends and the reader closes automatically. Since there is no error, catch does not run. Because every line read is written once, the running time of the program is proportional to the size of the file. In memory, only one line and the buffer are held at a time; memory use is constant however large the file is. This property makes it possible to process line by line even log files that are gigabytes in size.
Calling readLine() twice inside the loop: while (reader.readLine() != null) System.out.println(reader.readLine());. The call in the condition reads a line and throws it away, and the call in the body prints the next one. Half of the lines are lost, and for a file with an odd number of lines null is printed at the end. Each line is read once and kept in a variable.
8.4.8PrintWriter
PrintWriter is the most convenient way to write to text files. It has all the methods familiar from System.out: print, println, and printf. It converts numbers, characters, boolean values, and other types to text itself and writes them.
public class PrintWriterDemo {
public static void main(String[] args) {
PrintWriter writer = null;
try {
writer = new PrintWriter("newFile.txt");
writer.println("Hello, world!");
writer.println("This is a sample file.");
writer.printf(Locale.ROOT, "Pi is about %.2f%n", Math.PI);
writer.println(42);
} catch (IOException e) {
System.err.println("File error: " + e.getMessage());
e.printStackTrace();
} finally {
if (writer != null)
writer.close();
}
}
}After the program has run, the contents of newFile.txt are:
Hello, world!
This is a sample file.
Pi is about 3.14
42new PrintWriter("newFile.txt") creates the file if it does not exist. If the file exists, it erases its contents and writes from the beginning. If the file cannot be created, the constructor throws FileNotFoundException; the program catches it as an IOException. In printf, %.2f writes the number with two decimal places and %n writes the operating system's line terminator. The first argument, Locale.ROOT (java.util.Locale), makes the formatting independent of the locale.
Here is why Locale.ROOT is passed. If printf is called without a locale, it chooses the decimal separator according to the computer's locale. On a Turkish system it writes 3,14, on an English system 3.14. The same program produces different files on two machines. If a program is going to read the file later, this difference causes trouble: Double.parseDouble("3,14") fails. With Locale.ROOT the output is 3.14 on every machine. println(3.5), on the other hand, is already independent of the locale and always writes a period. The following experiment was run in the Turkish locale:
import java.io.*;
import java.util.Locale;
public class LocaleDemo {
public static void main(String[] args) throws Exception {
try (PrintWriter p = new PrintWriter("loc.txt")) {
p.printf("Pi is about %.2f%n", Math.PI);
p.printf(Locale.ROOT, "Pi is about %.2f%n", Math.PI);
p.println(3.5);
p.println('A');
p.println(true);
}
Show.main(new String[] {"loc.txt"});
}
}Pi is about 3,14
Pi is about 3.14
3.5
A
true
[50 bytes]PrintWriter has one more important property: its writing methods do not throw exceptions. If an I/O error occurs while writing, PrintWriter records it in an internal flag and silently continues. The error becomes visible only by calling checkError(). The trace in the buffering section shows this behavior. Finally, do not forget close(): PrintWriter contains a buffer, and if it is not closed the last things written may never reach the disk.
8.4.9FileWriter: writing and appending
FileWriter is the basic class for writing characters to files; it connects the writing function of the Writer class to a file. It has only the write(String), write(char[]), and write(int c) methods. Its text-formatting ability is limited: the line terminator (\n) is written separately, and numbers are first converted to strings. It is a lower-level and more flexible approach, which is why it is mostly wrapped in a BufferedWriter or a PrintWriter.
write(int c) is often confused. This method writes not the number but the character whose code is that number. w.write(65) writes A to the file; to write 65 you need w.write(String.valueOf(65)). The A65 in the last output line of the program below is the result of these two calls.
The most useful capability of FileWriter is the append mode. new FileWriter(name, true) adds to the end of the file without erasing it. If false is passed, or the second parameter is omitted, the file is reset.
public class FileWriterDemo {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("newFile.txt")) {
writer.write("Hello, world!\n");
writer.write("This is a FileWriter example.\n");
System.out.println("File created and data written.");
} catch (IOException e) {
System.err.println("File error: " + e.getMessage());
e.printStackTrace();
}
// true: append to the end of the file
try (FileWriter app = new FileWriter("newFile.txt", true)) {
app.write("Appended line.\n");
} catch (IOException e) {
System.err.println("File error: " + e.getMessage());
}
}
}File created and data written.The first try block creates the file and writes two lines. The second block opens the file with true, so it keeps the two existing lines and appends the third line at the end. When the program ends, newFile.txt is:
Hello, world!
This is a FileWriter example.
Appended line.Hello, world!
This is a FileWriter example.
Appended line.
[59 bytes]
A65The file is 59 bytes: the three lines have 56 characters, and the three line terminators add 3. All the characters are ASCII, so each takes one byte; letters such as ü would take two bytes each in UTF-8. Append mode is indispensable for log files: each time the program runs, the new records are added after the old ones. If true had been forgotten in the second try block, the first two lines would be erased and only “Appended line.” would remain in the file. Table 8.12 compares the three writer classes.
FileWriter | BufferedWriter | PrintWriter | |
|---|---|---|---|
| Writing methods | write | write, newLine() | print, println, printf |
| Writing a number | converted to a String first | converted to a String first | directly: println(42) |
| Buffer | small internal buffer | 8192-character buffer | depends on the stream it wraps |
| Error reporting | IOException | IOException | checkError() |
The choice depends on the job. If a formatted report or table is to be written, use PrintWriter; if many short writes are to be made, put a BufferedWriter in between. If errors should be reported at once as exceptions, BufferedWriter is preferable; with PrintWriter an error shows up only when checkError() is asked.
8.4.10Specifying the character encoding
Character streams that are not given an encoding use the default encoding. In Java 18 and later this is UTF-8. In older versions it was the operating system's setting; on Turkish Windows, Windows-1254. The same file could be read differently on two machines. In portable code the encoding is given explicitly. Since Java 11, FileReader and FileWriter have constructors that take an encoding. In Java 10 and earlier the same job was done with the bridge classes InputStreamReader and OutputStreamWriter.
public class EncodingRead {
public static void main(String[] args) throws IOException {
File file = new File("turkish.txt");
try (BufferedWriter writer = new BufferedWriter(
new FileWriter(file, StandardCharsets.UTF_8))) { // Java 11+
writer.write("Işık, şimşek, çiğ, öğrenci, Ünye");
}
try (BufferedReader right = new BufferedReader(
new FileReader(file, StandardCharsets.UTF_8))) {
System.out.println(right.readLine());
}
try (BufferedReader wrong = new BufferedReader(
new FileReader(file, StandardCharsets.ISO_8859_1))) {
System.out.println(wrong.readLine());
}
}
}Işık, şimşek, çiğ, öğrenci, Ünye
IÅık, ÅimÅek, çiÄ, öÄrenci, ÃnyeWhen the file is written in UTF-8 and read in UTF-8, the text comes back correctly. When the same bytes are read as ISO-8859-1, every Turkish letter turns into two separate characters. For example, the UTF-8 bytes of ş are C5 9F. In Latin-1, C5 is the letter Å, while 9F is a non-printable control character that does not show on the screen. So şimşek appears as ÅimÅek. This kind of garbling is called mojibake. An encoding error does not raise an exception; the program runs, but the data comes back corrupted.
Information is also lost when a character with no equivalent is written. If ş is given to a stream that writes ASCII, a question mark (?, 3F) is written, because ASCII has no equivalent for this letter. In UTF-8 the same letter would have been stored as C5 9F. This loss cannot be undone: the file now contains only a question mark.
Writing a file in one encoding and reading it in another. If a file produced by an old Windows program in Windows-1254 is read in Java 18 or later without naming an encoding, the Turkish letters turn into the � sign. If the encoding of the file is known, give it explicitly when reading: new FileReader(file, Charset.forName("windows-1254")).
8.5Buffering
The basic methods of streams work with small pieces. read() reads a byte or a byte array, and write() writes a byte or a byte array. If the program goes to the disk separately for every byte, the application slows down badly. This section explains the cause of the problem and its solution.
8.5.1Why buffer?
A disk is thousands of times slower than memory. Moreover, a disk access is not just transfer time. The program makes a system call, the operating system runs the device driver, and the result returns to the program. This fixed cost is roughly the same whether one byte or eight thousand bytes are read. Reading a thousand bytes with a thousand separate calls is therefore far more expensive than reading them with one call.
A buffer is an area in which data is temporarily collected in memory. Buffering is the technique of reducing the number of physical disk accesses by doing reads and writes in bulk through this area. When reading, the buffer is filled with a large piece at a time, and the program's small reads are served from the buffer. When writing, small writes accumulate in the buffer, and when the buffer is full it is sent to the disk in one go.
An everyday analogy explains the difference. To buy ten items at the market, you do not make a separate trip for each item; you put them all in one basket and carry them at once. The trip itself, the fixed cost, is paid once. Figure 8.13 compares unbuffered and buffered writing.
write() goes straight to the disk. (b) In a buffered stream, write() puts the bytes into the buffer in memory. (c) When the buffer is full, or when flush() or close() is called, the whole buffer is written to disk at once.8.5.2Buffered stream classes and flush
In Java, buffering is added with wrapper streams. There are four buffered classes (Table 8.13).
| Class | Stream it wraps | What it does |
|---|---|---|
BufferedInputStream | InputStream | Speeds up reading: when the buffer runs empty it reads 8192 bytes from the disk at once. |
BufferedReader | Reader | Does the same for characters; also adds readLine(). |
BufferedOutputStream | OutputStream | Speeds up writing: collects the data of write() in the buffer. |
BufferedWriter | Writer | Does the same for characters; also adds newLine(). |
A write buffer has a side effect: when write() returns, the data may not yet be on the disk. There are three moments when data goes to the disk. When the buffer fills up, it is emptied automatically. When flush() is called, the buffer is emptied to the disk immediately. When close() is called, flush() runs first and then the stream is closed. The following program shows this behavior by measuring the file size:
public class FlushDemo {
public static void main(String[] args) throws IOException {
File log = new File("log.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(log));
bw.write("Record 1");
System.out.println("before: " + log.length());
bw.flush();
System.out.println("after: " + log.length());
bw.close();
}
}before: 0
after: 8After bw.write("Record 1") returns, the file is still 0 bytes; the eight characters wait in the buffer of the BufferedWriter. After flush() the file is 8 bytes, one byte per character, because all of them are ASCII.
Not closing a buffered writer. If you write bw.write("data"); and never close the stream, the data stays in the buffer. The buffer is not flushed when the program ends either: when the JVM exits, it does not write the buffers of open streams to disk. The file looks empty. Call close() or flush(); the safest way is try-with-resources.
This mistake can really be measured. The following two programs were run one after the other. The first writes and ends without closing; the second looks at the size of the file:
note.txt size: 0program finished, note.txt size: 0Even after the program has ended, the file is 0 bytes. The five characters never reached the disk.
8.5.3Code trace: the buffer and flush
The following code fragment traces step by step the buffer beneath a PrintWriter. After every write, the size of the file is measured. The last two lines show what happens when you write to a closed stream.
File f = new File("log.txt");
PrintWriter pw = new PrintWriter(new FileWriter(f));
System.out.println("0: " + f.length());
pw.print("entry1;");
System.out.println("1: " + f.length());
pw.print("entry2;");
System.out.println("2: " + f.length());
pw.flush();
System.out.println("3: " + f.length());
pw.print("entry3;");
pw.close();
System.out.println("4: " + f.length());
pw.print("entry4;"); // closed: silently ignored
System.out.println("error? " + pw.checkError());0: 0
1: 0
2: 0
3: 14
4: 21
error? true| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 1: File f = new File("log.txt");2: PrintWriter pw = new PrintWriter(new FileWriter(f)); | f=log.txt, pw=PrintWriter | — |
| 2 | 3: System.out.println("0: " + f.length()); | f.length()=0 | 0: 0 |
| 3 | 4: pw.print("entry1;"); | buffer="entry1;" | — |
| 4 | 5: System.out.println("1: " + f.length()); | f.length()=0 | 1: 0 |
| 5 | 6: pw.print("entry2;");7: System.out.println("2: " + f.length()); | buffer="entry1;entry2;" | 2: 0 |
| 6 | 8: pw.flush(); | buffer="" | — |
| 7 | 9: System.out.println("3: " + f.length()); | f.length()=14 | 3: 14 |
| 8 | 10: pw.print("entry3;"); | buffer="entry3;" | — |
| 9 | 11: pw.close(); | pw=closed | — |
| 10 | 12: System.out.println("4: " + f.length()); | f.length()=21 | 4: 21 |
| 11 | 13: pw.print("entry4;"); // closed: silently ignored14: System.out.println("error? " + pw.checkError()); | pw.checkError()=true | error? true |
In the first step of Table 8.14, FileWriter creates the file; the file is empty. In this chain the buffer lives inside FileWriter. FileWriter uses an encoder that converts characters into bytes, and this encoder has a byte buffer. PrintWriter adds no buffer of its own; it passes what is written on to this buffer.
In the third and fifth steps, the print calls put seven characters each into the buffer but do not touch the disk. The file stays at 0 bytes. In the sixth step flush() empties the buffer to disk and 14 bytes are written. In the eighth step the third entry goes into the buffer. The close() in the ninth step first does a flush() and then closes the file. In the tenth step the file is 21 bytes. Had close() been forgotten, the third entry could have been lost.
flush() the file is 14 bytes. (c) After close() the file is 21 bytes.The eleventh step shows that PrintWriter does not throw exceptions. Calling print on a closed stream would normally require an IOException. PrintWriter does not fail loudly; the write silently fails and an internal flag is set. checkError() returns true. This behavior suits System.out, because wrapping every println in a try would be tedious. When writing to an important file, however, checkError() should be checked at the end, or a writer that throws exceptions should be chosen.
8.5.4Buffered reading
On the reading side, buffering is used in two ways: byte by byte and line by line. Suppose file.txt contains two lines: Java I/O and Buffer.
try {
FileInputStream fis = new FileInputStream("file.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
int b;
while ((b = bis.read()) != -1) {
System.out.print((char) b);
}
bis.close(); // also closes fis
} catch (IOException e) {
System.err.println("File error: " + e.getMessage());
}Output: reading byte by byte
Java I/O
BufferThis loop calls bis.read() once for every byte. But the disk is not read one byte at a time. On the first call the buffer is empty; BufferedInputStream reads up to 8192 bytes at once from the underlying FileInputStream. Later calls are served from the buffer without going to the disk. The line terminator is a byte too, and when printed with (char) it ends the line. That is why the output has two lines. This method gives correct results only for ASCII text; Turkish letters are broken because they take two bytes each.
try {
FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close(); // also closes fr
} catch (IOException e) {
System.err.println("File error: " + e.getMessage());
}The second fragment reads the same file line by line with BufferedReader and prints the same two lines. Because the character stream decodes the bytes, Turkish letters come through correctly too. In both fragments close() is applied only to the outermost stream: bis.close() closes the inner fis, and br.close() closes the inner fr.
These two fragments share a weakness. If an exception occurs during reading, the close() line is never reached and the file stays open. For this reason most of the programs in the rest of the chapter use try-with-resources.
8.5.5How much does buffering help?
The following program creates a 2 MB file and reads it twice byte by byte: first unbuffered, then buffered. The time is measured in milliseconds with System.nanoTime().
public class BufferTiming {
static long time(InputStream in) throws IOException {
long start = System.nanoTime();
while (in.read() != -1) { } // 1 byte at a time
in.close();
return (System.nanoTime() - start) / 1_000_000;
}
public static void main(String[] args) throws IOException {
File f = new File("big.dat");
try (FileOutputStream fos = new FileOutputStream(f)) {
fos.write(new byte[2 * 1024 * 1024]); // 2 MB
}
long t1 = time(new FileInputStream(f));
long t2 = time(new BufferedInputStream(new FileInputStream(f)));
System.out.println("Unbuffered: " + t1 + " ms");
System.out.println("Buffered : " + t2 + " ms");
f.delete();
}
}The output of the sample run in the slides is:
Unbuffered: 3151 ms
Buffered : 94 msWhile these notes were being prepared, the same program was run three more times. The times were 3194/58, 3241/62, and 3250/63 milliseconds. The times vary with the machine, the disk, and the operating system's cache; the ratio stays similar. On this machine buffered reading is more than fifty times faster.
The reason for the difference is the number of calls. The file is 2 MB, that is, 2 · 1024 · 1024 = 2,097,152 bytes. In the unbuffered stream every read() is a system call: 2,097,152 calls, plus one more that reports the end of the file. In the buffered stream there is one system call per 8192 bytes: 2,097,152 / 8192 = 256 calls that carry data and one call for the end of the file. The number of the program's own read() calls is the same in both cases; but in the buffered case these are ordinary method calls that read from an array in memory. The number of system calls drops by a factor of about 8000. The time drops only by a factor of about fifty, because a method call is still made for every byte. Reading block by block removes this cost as well.
8.6Other byte streams
The InputStream and OutputStream family has classes besides the file streams. They use an array in memory, another thread, or several streams as the source of data. Since they all carry the same read() and write() methods, they can be used wherever a file stream is expected.
8.6.1FileInputStream and reading in chunks
FileInputStream derives from InputStream and reads bytes directly from a file. It is a low-level class, suited to non-text data such as images and sound. It has two read methods:
read()reads a single byte and returns anintbetween 0 and 255. At the end of the file it returns −1.read(byte[] b)reads at mostb.lengthbytes into the array and returns the number of bytes it read. At the end of the file it returns −1. The returned number may be smaller than the length of the array.
public class ChunkRead {
public static void main(String[] args) throws IOException {
try (FileInputStream fis = new FileInputStream("file.txt")) {
byte[] buf = new byte[4];
int n;
while ((n = fis.read(buf)) != -1) {
System.out.println(n + ": " + new String(buf, 0, n));
}
}
}
}Suppose file.txt contains Hello, Java!: 12 bytes. Because the array holds 4 bytes, the file is read in three chunks:
4: Hell
4: o, J
4: ava!The second line, o, J, contains a comma and a space. new String(buf, 0, n) converts only the part of the array that was read, that is, n bytes starting at 0. In this example the file is an exact multiple of 4, so every chunk is full. Had the file been 13 bytes, the fourth read would have returned 1, and the last three cells of the array would still hold bytes left over from the previous chunk. Had new String(buf) been written, these stale bytes would have become part of the text.
Using FileInputStream for text is difficult. Multibyte characters such as Turkish letters can be split at a chunk boundary. If the word Gündüz is read in 2-byte chunks and each chunk is decoded separately as UTF-8, the two bytes of ü land in two different chunks:
[G�][�n][d�][�z]Each half-finished byte is an invalid UTF-8 sequence and turns into the � sign. For text files, character-based classes such as FileReader are more suitable; they keep a half character at a chunk boundary for the next read.
8.6.2In-memory streams
ByteArrayInputStream also derives from InputStream, but it reads not from a file but from a byte array in memory. It is fast because it touches no physical resource. It can only be read; to write to memory, its counterpart ByteArrayOutputStream is used. ByteArrayOutputStream collects the bytes written in a growing array; toByteArray() returns this array and toString() its text equivalent.
public class ByteArrayRead {
public static void main(String[] args) throws IOException {
byte[] arr = {74, 97, 118, 97}; // "Java"
ByteArrayInputStream bais = new ByteArrayInputStream(arr);
int b;
while ((b = bais.read()) != -1) {
System.out.print(b + "=" + (char) b + " ");
}
System.out.println();
// Writing to memory: ByteArrayOutputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(arr);
baos.write('!');
byte[] result = baos.toByteArray();
System.out.println(result.length + " bytes: " + baos);
}
}74=J 97=a 118=v 97=a
5 bytes: Java!The first loop reads the four bytes of the array. It prints each byte as a number and as a character: 74 = J, 97 = a, 118 = v. In the second part, four bytes and the character '!' are written to memory. The result is an array of 5 bytes.
These classes are useful in two situations. The first is testing a method that expects a stream without using files: a test can supply the desired input through a ByteArrayInputStream and collect the method's output in a ByteArrayOutputStream. The second is when the whole data is prepared in memory and then sent at once, for example over a network. Because all the data sits in memory, memory consumption becomes a problem with very large data.
8.6.3A deprecated class
java.io.StringBufferInputStream is an old class written to read bytes from a string. It has been deprecated since Java 1.1. The class still compiles, but the compiler issues a warning and its use is discouraged. Its problem is that it does not convert characters to bytes correctly: it takes only the low 8 bits of each character.
public class OldStream {
@SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException {
InputStream old = new StringBufferInputStream("ş€");
int b;
while ((b = old.read()) != -1) {
System.out.print(b + " ");
}
System.out.println();
byte[] right = "ş€".getBytes("UTF-8");
InputStream fresh = new ByteArrayInputStream(right);
while ((b = fresh.read()) != -1) {
System.out.print(b + " ");
}
System.out.println();
}
}95 172
197 159 226 130 172 The Unicode code of ş is 351, hexadecimal 015F. Its low 8 bits are 5F = 95, which is the character _. The code of € is 20AC and its low 8 bits are AC = 172. The two characters turn into two meaningless bytes and the real information is lost. The correct bytes are the UTF-8 bytes: 197 159 for ş and 226 130 172 for €. These bytes are obtained with "ş€".getBytes("UTF-8") and read with a ByteArrayInputStream. If the string has to be read as characters, StringReader is used. The @SuppressWarnings("deprecation") annotation silences the compiler warning in this example, which uses the old class on purpose.
8.6.4Pipes
PipedInputStream and PipedOutputStream provide safe communication of data between two threads. A thread is an independently progressing flow of execution inside the same program. One thread writes data with PipedOutputStream, and the other reads it with PipedInputStream. The two ends are connected with new PipedOutputStream(pis) (Figure 8.15).
PipedOutputStream; the bytes wait in a circular buffer of 1024 bytes; the reader thread reads them from the PipedInputStream.A pipe has four properties:
- Reading and writing are synchronized: if the pipe is empty the reader waits, and if it is full the writer waits.
- Data flows in one direction. Two-way communication needs two pipes.
- The buffer of a pipe is 1024 bytes by default.
- Using both ends in the same thread can cause a deadlock. When the buffer is full, the writer waits for the reader; but the reader is the same thread and never gets to run.
The following program creates a reader thread and a writer thread. The bodies of the threads are written as lambda expressions.
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream(pis);// Reader thread
Thread reader = new Thread(() -> {
try {
int b;
while ((b = pis.read()) != -1)
System.out.print((char) b);
System.out.println();
pis.close();
} catch (IOException e) {
e.printStackTrace();
}
});// Writer thread
Thread writer = new Thread(() -> {
try {
pos.write("Hello, pipe!".getBytes());
pos.close();
} catch (IOException e) {
e.printStackTrace();
}
});
reader.start();
writer.start();
writer.join();
reader.join();Hello, pipe!start() starts a thread; join() waits for it to finish. The two threads run at the same time, and which of them makes progress first can change from run to run. If the reader starts first, it waits in pis.read() because the pipe is empty. The writer writes the 12 bytes into the pipe and calls pos.close(). The reader's waiting read() call picks up the bytes in order. When the pipe has been emptied and the writer end is closed, read() returns −1 and the loop ends. The output is the same in every run, because a pipe preserves the order of the bytes. The program was run twice for these notes and printed the same line both times.
To see the deadlock warning in action, the buffer of the pipe is reduced to 4 bytes and the writer tries to write 6 bytes. Nobody is reading:
writer still running after 1.5 s? true, bytes in pipe: 4The writer writes the first 4 bytes and then waits because the pipe is full. After 1.5 seconds it is still waiting. Had the reader been the same thread, the program would have stopped forever. This experiment makes the writer a background thread so that the program can exit.
8.6.5SequenceInputStream
SequenceInputStream joins several InputStream objects end to end into one sequential stream (Figure 8.16). When the first stream ends and returns −1, reading automatically moves on to the second. In this way data from different sources is processed as if it were a single stream.
SequenceInputStream joins two file streams end to end. The reading program sees a single sequential stream.try {
FileInputStream is1 = new FileInputStream("file1.txt");
FileInputStream is2 = new FileInputStream("file2.txt");
SequenceInputStream sis = new SequenceInputStream(is1, is2);
int b;
while ((b = sis.read()) != -1)
System.out.print((char) b);
sis.close(); // also closes is1, is2
} catch (IOException e) {
System.err.println("Read error: " + e.getMessage());
}First file.
Second file.file1.txt contains the line First file. and file2.txt contains the line Second file.. The loop only calls sis.read() and does not notice the switch between the files. sis.close() closes both inner streams as well. If an error occurs in one of the streams during reading, an IOException is thrown and reading does not move on to the other stream.
8.7Copying files
Copying a file is a good exercise for learning streams: everything read from an input stream is written to an output stream. The same job can be done with different units: byte by byte, block by block, or line by line. This section compares the ways and shows the pitfalls of each.
8.7.1Copying byte by byte
The simplest copy writes every byte read from the source file to the destination file. Because byte streams do not care about the meaning of the bytes, this method copies every kind of file, whether text, an image, or an .exe, without corrupting it. To speed up reading and writing, the two streams are wrapped in buffered streams (Figure 8.17).
file.txt through FileInputStream and BufferedInputStream into the variable b, and from there through BufferedOutputStream and FileOutputStream to file2.txt.import java.io.*;
public class ByteCopy {
public static void main(String[] args) throws IOException {
File src = new File("file.txt");
File dst = new File("file2.txt");
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dst);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int b;
// Read a byte; -1 at end of file.
while ((b = bis.read()) != -1)
bos.write(b); // write it out
bos.close();
bis.close();
System.out.println(dst.length() + " bytes copied");
}
}The copy loop is a single line: while ((b = bis.read()) != -1) bos.write(b);. bis.read() reads a byte and returns −1 at the end of the file. bos.write(b) writes the byte just read to the output stream. The value read must be kept in an int variable. The reason is to tell −1 apart from a byte with the value 255. read() can return every value in the range 0–255 as a valid byte; since −1 lies outside this range, it reports the end of the file without ambiguity.
Storing the result of read() in a byte: byte b; while ((b = (byte) in.read()) != -1). In Java, byte is signed and takes values between −128 and 127. A byte with the value 255, that is FF, becomes −1 through the (byte) cast. The loop mistakes this byte for the end of the file and stops; the rest of the file is not copied. The correct type is int.
The effect of the mistake can be seen in a small experiment. If the three-byte array {10, (byte) 255, 20} is read with this loop, only the first byte is processed:
processed: 1Because the FF byte rarely occurs in text files, this mistake goes unnoticed in experiments with text files. In images or compressed files, FF is common, and the copy is cut off halfway.
8.7.2Code trace: byte-by-byte copy
Suppose file.txt contains four bytes: Java. Table 8.15 gives the state of the two buffers and the destination file at each step of the program.
| Step | Line | b | bis buffer | bos buffer | file2.txt | What happened? |
|---|---|---|---|---|---|---|
| 1 | 5–6 | — | — | — | none | The two File objects hold only paths. |
| 2 | 7–8 | — | — | — | 0 bytes | FileOutputStream creates the destination file; if it exists, its contents are erased. |
| 3 | 9–10 | ? | empty | empty | 0 bytes | The streams are wrapped in buffered streams. |
| 4 | 13 | 74 | Java | empty | 0 bytes | The buffer is empty; one disk read brings 4 bytes. The first byte 'J' is returned. |
| 5 | 14 | 74 | Java | J | 0 bytes | write puts the byte into the output buffer. |
| 6–7 | 13–14 | 97 | Java | Ja | 0 bytes | The byte comes from the buffer; the disk is not touched. |
| 8–9 | 13–14 | 118 | Java | Jav | 0 bytes | The byte comes from the buffer. |
| 10–11 | 13–14 | 97 | Java | Java | 0 bytes | The output buffer holds 4 bytes. |
| 12 | 13 | −1 | empty | Java | 0 bytes | The buffer is used up; the second disk read reports the end of the file. |
| 13 | 15 | −1 | empty | empty | 4 bytes | bos.close() first does a flush(): the 4 bytes go to disk in one write. |
| 14 | 16 | −1 | — | — | 4 bytes | The input streams are closed. |
| 15 | 17 | −1 | — | — | 4 bytes | Output: 4 bytes copied |
read() brings all four bytes into the input buffer. (b) Four bytes wait in the output buffer; the destination file is still 0 bytes. (c) After close(), the four bytes are on disk.The most important result of the trace is that although the program makes five read() calls and four write() calls, the disk is touched far less often. To verify this, subclasses of FileInputStream and FileOutputStream were written. These subclasses count and print every call that goes to the disk:
disk read(arr, 0, 8192) -> 4
disk read(arr, 0, 8192) -> -1
disk write(arr, 0, 4)
buffered: 2 reads, 1 write
disk read() -> 74
disk read() -> 97
disk read() -> 118
disk read() -> 97
disk read() -> -1
unbuffered: 5 reads, 4 writesThe buffered copy makes two reads from the disk. The first asks for 8192 bytes and gets four. The second happens after the buffer is used up and reports the end of the file (−1). Only one write goes to the disk. The unbuffered copy, in contrast, needs one read and one write for every byte, plus one more read for the end of the file: five reads, four writes. For a four-byte file the difference is small. For a one-megabyte file, the unbuffered copy makes over a million read and write calls. The buffered copy finishes the job with 129 reads and 128 writes, about 260 calls.
8.7.3Copying block by block
Buffered streams reduce disk access, but the program itself still calls read() and write() once per byte. The faster way is to read the data in blocks into the program's own array. read(byte[] buf) tries to fill the array and returns the number of bytes it read. write(buf, 0, size) writes only the first size bytes of the array.
public class BlockCopy {
public static void main(String[] args) throws IOException {
// Data is read in 16K chunks
byte[] buf = new byte[1024 * 16];
File src = new File("file.txt");
File dst = new File("file2.txt");
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dst);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int size;
// Read up to 16K; -1 at end of file.
while ((size = bis.read(buf)) > -1)
bos.write(buf, 0, size); // write the chunk
bos.close();
bis.close();
System.out.println(dst.length() + " bytes copied");
}
}For a 40,000-byte file the output is:
40000 bytes copiednew byte[1024 * 16] creates a 16 KB array. The data is processed in chunks of this size, so the program's memory use stays constant no matter how large the file is. A 40,000-byte file arrives in three reads: 16,384, 16,384, and 7,232 bytes. The last chunk does not fill the whole array. An experiment with a 40,000-byte file of random bytes, run for these notes, confirms the chunk sizes and that the copy is identical to the source:
chunks read: 16384 16384 7232
identical: trueThe loop condition has the form > -1; it means the same as != -1, because read never returns a value smaller than −1. A return value of 0 from read(byte[]) is possible only when the array has length 0.
8.7.4Code trace: block copy
In block copying, the handling of the last chunk is critical. To keep the trace small, it uses a 16-byte array and a 39-byte file; in real programs the array is 8–16 KB. This time no buffered streams are used, and the resources are opened with try-with-resources.
public class BlockTrace {
public static void main(String[] args) throws IOException {
byte[] buf = new byte[16];
try (InputStream in = new FileInputStream("file.txt");
OutputStream out = new FileOutputStream("file2.txt")) {
int size;
while ((size = in.read(buf)) > -1) {
out.write(buf, 0, size);
System.out.println("size = " + size);
}
}
long n = new File("file2.txt").length();
System.out.println("Done: " + n + " bytes");
}
}| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 3: byte[] buf = new byte[16]; | buf=byte[16] | — |
| 2 | 4: try (InputStream in = new FileInputStream("file.txt");5: OutputStream out = new FileOutputStream("file2.txt")) { | buf=byte[16] | — |
| 3 | 7: while ((size = in.read(buf)) > -1) { | size=16 | — |
| 4 | 8: out.write(buf, 0, size); | size=16 | — |
| 5 | 9: System.out.println("size = " + size); | size=16 | size = 16 |
| 6 | 7: while ((size = in.read(buf)) > -1) { | size=16 | — |
| 7 | 8: out.write(buf, 0, size); | size=16 | — |
| 8 | 9: System.out.println("size = " + size); | size=16 | size = 16 |
| 9 | 7: while ((size = in.read(buf)) > -1) { | size=7 | — |
| 10 | 8: out.write(buf, 0, size); | size=7 | — |
| 11 | 9: System.out.println("size = " + size); | size=7 | size = 7 |
| 12 | 7: while ((size = in.read(buf)) > -1) { | size=-1 | — |
| 13 | 13: System.out.println("Done: " + n + " bytes"); | size=-1, n=39 | Done: 39 bytes |
In the first two iterations of Table 8.16, read(buf) fills the array and returns 16. write(buf, 0, 16) writes the 16 bytes that were read. In the second iteration the new 16 bytes overwrite the same array; the array is reused in every iteration. In the third iteration only 7 bytes are left in the file. read refreshes the first 7 cells of the array and returns 7. The remaining 9 cells still hold bytes left over from the previous block.
write(buf, 0, 7) writes only the 7 bytes that were read.Had write(buf) been written here instead of write(buf, 0, size), all 16 bytes of the array would have been written. The 9 old bytes would also enter the copy, and the copy would be 16 + 16 + 16 = 48 bytes. An experiment with the same file confirms this. The last 9 bytes of the copy are the fragment kislar ve left over from the second block:
with write(buf): 48 bytes
last 9 bytes: kislar ve | real last block: tamponIn the fourth iteration read returns −1, the condition > -1 becomes false, and the loop ends. The resources are closed, and the copy has the same length as the source: 16 + 16 + 7 = 39 bytes. The number of reads and writes is the ceiling of the file length divided by the array length: ⌈39/16⌉ = 3. A one-megabyte file is copied in 64 iterations with a 16 KB array.
Writing out.write(buf); in a block copy. In the last block the array is not completely filled; the stale data at the end of the array also goes into the copy, and the copy becomes larger than the source. The correct call is always write(buf, 0, size), where size is the value read returned last. The same rule applies when converting to text: new String(buf, 0, size).
8.7.5Copying line by line
Text files can also be copied line by line. This way works with character streams and is useful when the lines have to be processed while being copied: filtering, numbering, or modifying them, for example.
public class LineCopy {
public static void main(String[] args) throws IOException {
File src = new File("file.txt");
File dst = new File("file2.txt");
FileReader fr = new FileReader(src);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(dst);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
String line;
// read a line until end of file
while ((line = br.readLine()) != null)
pw.println(line); // write the line
pw.close();
br.close();
System.out.println("Copied: " + dst.getName());
}
}Copied: file2.txtOn the reading side there is FileReader and BufferedReader, and on the writing side the chain FileWriter, BufferedWriter, and PrintWriter. The loop takes each line with readLine() and writes it with println. pw.close() closes the whole chain, including bw and fw.
This method has two limits. First, it is suitable only for text files. If a binary file goes through a character stream, the encoding conversion corrupts the bytes. Second, the copy may not be byte-for-byte identical. readLine() discards the line terminator, while println adds the system's line terminator: \r\n on Windows and \n on Linux. If the last line of the source has no terminator, the copy has one extra. The experiment below was run on Windows with a 41-byte file whose last line ends without a line terminator; the copy takes 43 bytes:
Copied: file2.txt
41 -> 43 bytes; line.separator length 2If the line terminators of the source were in Linux form (\n), each line of the copy made on Windows would be one byte longer. So whenever a byte-for-byte identical copy is needed, byte streams are always used.
8.7.6Downloading a web page
The source of a copy loop does not have to be a file. The following program downloads a web page and saves it to disk. This time the source is the network: url.openStream() returns an InputStream. The rest of the loop is the same as in file copying.
public class WebDownload {
public static void main(String[] args) throws IOException {
URL url = URI.create("https://sercankulcu.github.io/").toURL();
BufferedInputStream bis = new BufferedInputStream(url.openStream());
FileOutputStream fos = new FileOutputStream(new File("copy.html"));
BufferedOutputStream bos = new BufferedOutputStream(fos);
for (int c = bis.read(); c != -1; c = bis.read()) {
bos.write(c);
}
bis.close();
bos.close();
System.out.println("copy.html: " + new File("copy.html").length() + " bytes");
}
}copy.html: 14283 bytesThe size in the output varies with the page and the moment of download. This value is the size of the page as it came from the server when these notes were prepared. This time the copy loop is written with for: the first read happens in the initialization part, the byte is written if it is not −1, and the update part reads again. It does the same job as a loop written with while.
The use of URI.create(…).toURL() in the program is deliberate. The new URL(String) constructor has been deprecated since Java 20; this two-step way is recommended instead. URI checks the syntax of the address more strictly. If the network connection cannot be made, or the server's certificate cannot be verified, openStream() throws a subclass of IOException. This program also leaves the error to the JVM with the throws IOException in the header of main.
8.7.7Shortcuts and a comparison
There is no need to rewrite the copy loop every time. The Java library has two methods that do this job. in.transferTo(out) (Java 9+) transfers all the bytes of an input stream to an output stream and returns the number of bytes transferred. Files.copy(source, target) (Java 7+) copies a file directly to another file. Both do block copying internally.
public class QuickCopy {
public static void main(String[] args) throws IOException {
// Java 9+: transferTo
try (InputStream in = new FileInputStream("file.txt");
OutputStream out = new FileOutputStream("file2.txt")) {
long n = in.transferTo(out);
System.out.println(n + " bytes transferred");
}
// Java 7+: Files.copy
Files.copy(Path.of("file.txt"), Path.of("file3.txt"),
StandardCopyOption.REPLACE_EXISTING);
System.out.println(Files.size(Path.of("file3.txt")) + " bytes copied");
}
}4 bytes transferred
4 bytes copiedIf the target file exists, Files.copy throws FileAlreadyExistsException unless overwriting is permitted. This behavior is a safeguard: it prevents an existing file from being overwritten by accident. To overwrite, StandardCopyOption.REPLACE_EXISTING is passed as the third argument. An attempt made without the option shows the exception and that the target file is unchanged:
java.nio.file.FileAlreadyExistsException: k2.txt
k2.txt: oldTable 8.17 compares the copying methods, and Figure 8.20 shows how different the call counts are for a 1 MB file.
| Method | Unit | When it fits |
|---|---|---|
Byte by byte (read() / write(int)) | 1 byte | for learning; very slow without buffering |
Block by block (read(byte[])) | 8–16 KB | any kind of file, fast |
Line by line (readLine / println) | 1 line | text only; when processing lines |
in.transferTo(out) (Java 9+) | block | one-line copy between two streams |
Files.copy(source, target) (Java 7+) | block | shortest way from file to file |
read calls when copying a 1 MB file (bar lengths are logarithmic). Byte-by-byte reading makes 1,048,576 calls, and block reading with an 8 KB array makes 128; Files.copy is a single method call.Whichever method is chosen, three rules apply: work with buffering, close the streams (preferably with try-with-resources), and handle IOException. In a real program, use Files.copy for a file-to-file copy and transferTo for a copy between two streams. A hand-written block loop is needed when something has to be done with the data while it is copied, for example to show a progress bar or to encrypt the bytes.
8.8Random access
Streams are all sequential: they read or write data from beginning to end. Some tasks, however, require going directly to a record in the middle of a file. To read the grade of the thousandth student in a student file, reading the previous 999 records is an unnecessary burden.
8.8.1Sequential and random access
In sequential access, each read or write continues from where the previous one ended; going back needs special support (for example mark/reset, within a limited buffer), and you cannot jump freely to a position. In random access, the program jumps to a desired position in the file and reads or writes from there. The position is the number of bytes from the start of the file, counting from 0.
Sequential access is like a cassette tape: to reach a song, the earlier ones have to be wound past. Random access is like a vinyl record: the needle is placed wherever you want (Figure 8.21). Streams (FileInputStream, BufferedReader, and so on) are all sequential. Sequential access is used when the structure of the file is unknown or when the whole file is being processed; copying is the typical example.
seek.Random access can be used when the size and position of the records are known. If all records have the same size, the position of record number k is found by multiplication: position = k · record size (numbering starts at 0). This way is very convenient for reading or modifying a particular record in place. The fixed-size requirement is important. In a text file whose lines have different lengths, where the kth line starts cannot be computed.
8.8.2RandomAccessFile
In Java, random access is done with the class java.io.RandomAccessFile. This class differs from streams: a single object both reads and writes, and it is not part of the InputStream/OutputStream hierarchy. Inside the object there is a file pointer. Every read and write takes place at the position the pointer indicates and advances the pointer by the number of bytes read or written. Table 8.18 lists the main members of the class.
| Member | Purpose |
|---|---|
RandomAccessFile(String name, String mode) | mode "r": read only; "rw": read and write (the file is created if it does not exist) |
seek(long pos) | moves the file pointer to the given position |
getFilePointer() | distance of the pointer from the start of the file (bytes) |
length() | length of the file (bytes) |
read() / write(int b) | reads one byte (returned as an int) / writes one byte |
readInt(), writeInt(int), readDouble() … | reads and writes primitive types in binary (int: 4 bytes) |
close() | releases the system resources |
int records. seek(2 * 4) moves the pointer to byte 8; readInt() reads record number 2. Byte position = record number · record size.The following program reads the same file first sequentially and then with random access. Here data is a 124-byte data file. For these notes the program was run with a file whose first byte is 1 and whose bytes 100–103 are 00 00 01 00.
public class RandomAccess {
public static void main(String[] args) throws IOException {
// Sequential access
FileInputStream seq = new FileInputStream("data");
int first = seq.read();
seq.close();
System.out.println("First byte: " + first);
// Random access
RandomAccessFile raf = new RandomAccessFile("data", "rw");
// Go to 100 bytes from the start
raf.seek(100);
// Read a 4-byte int from position 100
int value = raf.readInt();
System.out.println("int at 100: " + value);
raf.close();
}
}First byte: 1
int at 100: 256FileInputStream reads from the start of the file and gives the first byte, 1. seek(100) moves the pointer to position 100, that is, to the 101st byte, because positions start at 0. The four bytes there are 00 00 01 00. readInt() reads the most significant byte first: 0 · 224 + 0 · 216 + 1 · 28 + 0 = 256.
At the boundaries, RandomAccessFile behaves slightly differently from streams. The pointer can be moved beyond the end of the file; if a write is made there, the file grows up to that point and the bytes in between are undefined (they are zero in this experiment). At the end of the file, read() returns −1, whereas readInt() throws EOFException. The mode can only be "r", "rw", "rws", or "rwd"; "w" is invalid:
seek(10)+write: length 11, pointer 11
first byte: 0
read() at the end: -1
readInt() at the end: EOFException
mode r, no such file: FileNotFoundException
mode w: Illegal mode "w" must be one of "r", "rw", "rws", or "rwd"8.8.3Code trace: random access to records
The following program writes five grades to a file as int values. It then reads the third grade directly, modifies the fourth grade in place, and adds up all the grades.
import java.io.*;
public class Records {
public static void main(String[] args) throws IOException {
RandomAccessFile f = new RandomAccessFile("n.dat", "rw");
int[] grades = {70, 85, 90, 45, 60};
for (int n : grades)
f.writeInt(n); // 4 bytes each
System.out.println("Length: " + f.length());
f.seek(2 * 4); // go to record 3
System.out.println("Grade 3: " + f.readInt());
System.out.println("Position: " + f.getFilePointer());
f.seek(3 * 4); // record 4
f.writeInt(50); // 50 replaces 45
f.seek(0);
int total = 0;
while (f.getFilePointer() < f.length())
total += f.readInt();
System.out.println("Total: " + total);
f.close();
}
}| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 5: RandomAccessFile f = new RandomAccessFile("n.dat", "rw"); | — | — |
| 2 | 6: int[] grades = {70, 85, 90, 45, 60}; | grades=[70, 85, 90, 45, 60] | — |
| 3 | 7: for (int n : grades)8: f.writeInt(n); // 4 bytes each | n=70 | — |
| 4 | 7: for (int n : grades)8: f.writeInt(n); // 4 bytes each | n=60 | — |
| 5 | 9: System.out.println("Length: " + f.length()); | — | Length: 20 |
| 6 | 10: f.seek(2 * 4); // go to record 3 | — | — |
| 7 | 11: System.out.println("Grade 3: " + f.readInt()); | — | Grade 3: 90 |
| 8 | 12: System.out.println("Position: " + f.getFilePointer()); | — | Position: 12 |
| 9 | 13: f.seek(3 * 4); // record 4 | — | — |
| 10 | 14: f.writeInt(50); // 50 replaces 45 | — | — |
| 11 | 15: f.seek(0); | total=0 | — |
| 12 | 17: while (f.getFilePointer() < f.length())18: total += f.readInt(); | total=355 | — |
| 13 | 19: System.out.println("Total: " + total); | total=355 | Total: 355 |
In the first step of Table 8.19, mode "rw" creates the file if it does not exist; the pointer is at 0. In the loop each writeInt writes 4 bytes and advances the pointer by 4. When the loop ends, the file is 5 · 4 = 20 bytes and the pointer is at the end of the file, at 20. The actual bytes of the file are:
20: 00 00 00 46 00 00 00 55 00 00 00 5A 00 00 00 32 00 00 00 3C46 = 70, 55 = 85, and 5A = 90. The fourth record on this line is 32 = 50, because the bytes were printed after the program finished; the value first written was 45, that is, 2D.
In the sixth step, seek(2 * 4) moves the pointer to byte 8. This is the start of the third record, record number 2. The earlier records are not read; the program jumps straight there. readInt() reads bytes 8–11 and returns 90. The pointer advances to 12. The seek(3 * 4) in the ninth step moves the pointer to 12; the pointer is already there. In the tenth step, writeInt(50) is written in place of 45. The rest of the file does not change. This cannot be done with a sequential stream: to change a record in the middle of the file, the whole file would have to be rewritten.
seek(8) moves the pointer to the start of the third record. (b) writeInt(50) modifies the fourth record in place.In the last steps, seek(0) returns to the start. The loop reads int values until the pointer reaches the file length: 70 + 85 + 90 + 50 + 60 = 355. The program's output is the same as the values on the slides.
Length: 20
Grade 3: 90
Position: 12
Total: 355In terms of cost, the difference is clear. To reach record number k with a sequential stream, the preceding k records must be read; the time is proportional to k, O(k). With random access the position is computed by a multiplication and a single seek is made; the time is independent of the record number, O(1).
In a student file, let each record consist, in order, of an int student number, a double average, and an int credit count. Records are numbered from 0. How is the average of record 37 read?
The record size is 4 + 8 + 4 = 16 bytes. Record 37 starts at byte 37 · 16 = 592. Within the record, the average comes after the student number, 4 bytes past the start of the record. Write f.seek(37 * 16 + 4); double avg = f.readDouble();. After the read, the pointer is at 592 + 4 + 8 = 604, which is the start of the credit field of the same record. If one of the records had been written with float instead of double, all the position calculations would break. Random access requires the file format to be known exactly.
8.9Serialization
So far numbers and text have been written to files. In an object-oriented program, however, what we want to store is often an object: the state of a game, a student record, a settings object. Writing and reading back every field of an object one by one is tedious. Java offers a mechanism that does this in a single call.
8.9.1What is serialization?
Serialization is converting the state of an object, that is, the values of its fields, into a sequence of bytes. This byte sequence can be written to a file or carried to another environment over a network. Rebuilding an object from a byte sequence is called deserialization.
For the objects of a class to be serializable, the class must implement the java.io.Serializable interface. This interface has no methods at all. Such interfaces are called marker interfaces; their only job is to mark the class as "serializable". The serialization mechanism looks for this mark before writing the object.
Serialization involves three flows (Figure 8.24). An object sits in memory. ObjectOutputStream.writeObject converts it to bytes; the file begins with the magic number AC ED. ObjectInputStream.readObject builds a new object from these bytes. The new object has the same values but is a different object.
writeObject converts the Student object in memory into a 74-byte array and writes it to the file; readObject builds an object with the same state but a different identity.Serialization is used in game saves, in caches, and in sending objects over a network to another JVM. Its format is specific to Java and tightly bound to the structure of the class. For this reason, text formats such as JSON are generally preferred for data that will be stored for a long time or shared with other languages. Moreover, deserializing data that comes from an untrusted source can create a security hole, because during deserialization the program's classes are instantiated with unknown data.
8.9.2A serializable class
import java.io.Serializable;
class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}Three details in the class are related to serialization:
implements Serializablemakes the class serializable. No method has to be written.serialVersionUIDis the version identifier of the class. This number is also written into the serialized bytes. When reading, the number in the file is compared with the number of the class in the program; if they differ,InvalidClassExceptionis thrown. Writing the number by hand is recommended. If it is not written, the serialization mechanism computes it from the structure of the class; when a field or method is added to the class, the computed number changes and old files can no longer be read.- The fields must be serializable too.
Stringandintare serializable. If the type of a field is notSerializable,NotSerializableExceptionis thrown during writing.
The version check really works. When a file written with serialVersionUID = 1L is read with version 2L of the same class, this exception results:
java.io.InvalidClassException: Student; local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 28.9.3Writing an object and reading it back
ObjectOutputStream is used to serialize and ObjectInputStream to deserialize. Both are wrapper streams and wrap a file stream.
// Serialize
try (ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("student.ser"))) {
Student student = new Student("Ahmet", 20);
out.writeObject(student);
System.out.println("Serialization succeeded.");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("student.ser: " + new File("student.ser").length() + " bytes");
// Deserialize
try (ObjectInputStream in = new ObjectInputStream(
new FileInputStream("student.ser"))) {
Student student = (Student) in.readObject();
System.out.println("Student: " + student);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}Serialization succeeded.
student.ser: 74 bytes
Student: Student [name=Ahmet, age=20]The first block creates a Student object and writes it with writeObject. The file is 74 bytes. That seems like a lot for this small object. But the file holds not only the values of the two fields but also the definition of the class: the class name, the version identifier, and the names and types of the fields. The bytes of the file show this:
AC ED 00 05 73 72 00 07 | ····sr··Student···········I··ageL··namet··Ljava/lang/String;xp····t··AhmetThe first four bytes AC ED 00 05 are the stream header: the magic number and the version of the serialization protocol. In the readable part you can see Student, age, name, java/lang/String, and Ahmet.
The second block reads the object back. readObject returns a value of type Object; that is why the cast (Student) is needed. readObject can throw two checked exceptions: IOException and ClassNotFoundException. The second is thrown when the class in the file cannot be found in the program. The program catches both together with a multi-catch. If ClassNotFoundException is neither caught nor declared, the code does not compile:
Main.java:6: error: unreported exception ClassNotFoundException; must be caught or declared to be thrown
Object o = g.readObject();
^
1 errorIf the cast is made to the wrong type, ClassCastException is thrown at run time; if the file is not serialized data at all, StreamCorruptedException is thrown:
ClassCastException
StreamCorruptedException: invalid stream header: 6D6572686D657268 is the first four bytes of a plain text file: m, e, r, h. Because the stream header AC ED is missing, the read is rejected right at the start.
8.9.4transient and static fields
Not every field of an object should be stored. A password should not be stored. A temporary cache or an open file connection cannot even be stored. Such fields are marked with the keyword transient.
A field marked transient is skipped during serialization. When the object is read back, this field gets the default value of its type: null for references, 0 for numbers, and false for boolean. static fields are never serialized, because they belong to the class, not to the object.
class Account implements Serializable {
private static final long serialVersionUID = 1L;
static int count;
private String name;
private transient String password; // not written
Account(String name, String password) {
this.name = name;
this.password = password;
}
public String toString() {
return "Account [name=" + name + ", password=" + password + "]";
}
}The experiment below writes an Account object, changes the static counter, and reads the object back:
Account k = new Account("ayse", "secret12");
Account.count = 5;
ObjectOutputStream c = new ObjectOutputStream(
new FileOutputStream("k.ser"));
c.writeObject(k);
c.close();
Account.count = 99; // static: per class
ObjectInputStream g = new ObjectInputStream(
new FileInputStream("k.ser"));
Account copy = (Account) g.readObject();
g.close();
System.out.println(copy);
System.out.println("count = " + Account.count);
System.out.println("same object? " + (copy == k));Account [name=ayse, password=null]
count = 99
same object? falseEach of the three lines shows one rule. password came back as null, because the transient field was not written to the file. count is 99, because the file does not contain count and reading cannot change it; the value is the last one in memory. copy == k is false, because readObject builds a new object.
8.9.5Code trace: serialization
When the same piece of code is traced step by step, the size of the file and the state of the objects can be seen at every moment. The trace program added two lines to the code on the slides so that it also prints the file size:
[after header: 4]
[k.ser: 63]
Account [name=ayse, password=null]
count = 99
same object? false| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 1: Account k = new Account("ayse", "secret12"); | k=Account@1 | — |
| 2 | 2: Account.count = 5; | k=Account@1, Account.count=5 | — |
| 3 | 3: ObjectOutputStream c = new ObjectOutputStream(4: new FileOutputStream("k.ser")); | c=ObjectOutputStream | — |
| 4 | 5: c.writeObject(k); | c=ObjectOutputStream | — |
| 5 | 6: c.close(); | c=closed | — |
| 6 | 7: Account.count = 99; // static: per class | Account.count=99 | — |
| 7 | 8: ObjectInputStream g = new ObjectInputStream(9: new FileInputStream("k.ser")); | g=ObjectInputStream | — |
| 8 | 10: Account copy = (Account) g.readObject(); | copy=Account@2 | — |
| 9 | 12: System.out.println(copy); | copy=Account@2 | Account [name=ayse, password=null] |
| 10 | 13: System.out.println("count = " + Account.count); | Account.count=99 | count = 99 |
| 11 | 14: System.out.println("same object? " + (copy == k)); | result of copy == k: false | same object? false |
In the first step of Table 8.20, a new Account object is created on the heap; name and password are filled in. The static count is a field of the class and has a single copy. In the third step the ObjectOutputStream is opened and immediately writes the 4-byte stream header to the file. In the fourth step writeObject writes the class definition and the fields; the file becomes 63 bytes. The transient password and the static count are not written.
writeObject writes only name; the file is 63 bytes. (b) readObject builds a new object; password is null.The eighth step carries a subtle point of serialization. readObject builds a new object on the heap but does not call the constructor of Account. The values of the fields come directly from the file. Fields that are not in the file keep their default values. This is why the initial value in the declaration of a transient field does not take effect either: even if transient int b = 2; is written, b is 0 in the object read back. In the last step two references are compared; although their contents are similar, they are two separate objects.
Forgetting Serializable. If the class written with writeObject, or the type of one of its fields, does not implement this interface, an exception such as java.io.NotSerializableException: Car is thrown at run time. The compiler does not check this with default settings. The fix is to make the class Serializable or to mark the field transient.
8.10NIO
Java NIO (New I/O) arrived with Java 1.4 in the java.nio package. It offers higher performance and flexibility than the classic java.io streams. NIO.2 (java.nio.file), which came with Java 7, added the Path and Files classes for file operations.
8.10.1The building blocks of NIO
NIO is built on four basic concepts:
- Buffer (
Buffer): memory areas that hold data temporarily. - Channel (
Channel): connection objects that manage input and output operations and can be bidirectional. - Selector (
Selector): an object that monitors multiple channels with a single thread and reports which are ready. - Path (
Path): the NIO.2 class that represents file and directory paths.
8.10.2Stream or channel?
In classic I/O the program works with a stream, and data flows in one direction, byte by byte or character by character. In NIO the program writes to a buffer or reads from a buffer, and a channel moves whole buffers of data between the buffer and the source or destination (Figure 8.26).
Classic I/O (java.io) | NIO (java.nio) | |
|---|---|---|
| Core concept | stream | channel and buffer |
| Direction | one way: input or output | a channel can be two-way |
| Unit | byte or character | a block of a buffer's size |
| Waiting | always blocking | a non-blocking mode exists too |
| Many connections | one thread per connection | a single thread and a selector |
| When to use | simple file and console tasks | servers with many connections, large files |
The non-blocking mode is the most important difference of NIO. With a classic stream, read() waits until data arrives, and the thread cannot do anything else in the meantime. A server with a thousand clients has to start a thousand threads. A non-blocking channel, by contrast, returns immediately if there is no data. A single thread can therefore poll many channels in turn.
8.10.3Buffers and their properties
An NIO buffer is a fixed-size block of memory that holds data temporarily: an array plus position information over it. It has four properties. The capacity is the maximum number of elements it can hold and never changes. The position is the index at which the next read or write takes place. The limit is the first index that cannot be read or written. The mark is a position saved with mark(); reset() returns to it. Always 0 ≤ mark ≤ position ≤ limit ≤ capacity.
remaining() = limit − position = 4.There is a buffer class for each primitive type: ByteBuffer, CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer, and DoubleBuffer. Because channels carry bytes, ByteBuffer is used most. A buffer is created either with ByteBuffer.allocate(1024) or by wrapping an existing array with ByteBuffer.wrap(array).
A buffer has two modes. In write mode the position points to the next empty cell and the limit to the capacity. In read mode the position points to the next cell to read and the limit to the end of the data written. The modes are switched with flip(). The buffer does not know which mode it is in; the programmer has to keep track of it.
8.10.4ByteBuffer examples
public class BufferDemo {
public static void main(String[] args) {
// Create a 1 KB ByteBuffer
ByteBuffer buffer = ByteBuffer.allocate(1024);
// Write data
buffer.put("Hello from NIO".getBytes());
System.out.println("after put : " + buffer);
// Switch to read mode
buffer.flip();
System.out.println("after flip : " + buffer);
// Read the data
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
System.out.println();
}
}after put : java.nio.HeapByteBuffer[pos=14 lim=1024 cap=1024]
after flip : java.nio.HeapByteBuffer[pos=0 lim=14 cap=1024]
Hello from NIOput writes 14 bytes and advances the position to 14. flip() pulls the limit down to 14 and returns the position to 0; the buffer is now in read mode. hasRemaining() asks whether the position is smaller than the limit. The loop reads exactly 14 bytes. Had flip() been forgotten, reading would start at position 14 and 1010 empty bytes would be read.
This loop gives the right result only for ASCII text. Converting each byte to a char on its own corrupts multibyte characters:
public class BufferUmlaut {
public static void main(String[] args) {
ByteBuffer b = ByteBuffer.allocate(64);
b.put("Dünya".getBytes(StandardCharsets.UTF_8));
b.flip();
while (b.hasRemaining())
System.out.print((char) b.get()); // wrong
System.out.println();
b.rewind();
System.out.println(StandardCharsets.UTF_8.decode(b)); // right
}
}Dᅢᄐnya
Dünya"Dünya" is 6 bytes in UTF-8; ü = C3 BC. (char) b.get() converts a signed byte value to char. C3 as a byte is −61, and when it is converted to char the sign bit is extended: U+FFC3, that is, ᅢ. BC likewise becomes ᄐ. To decode the text, use Charset.decode. Because rewind() brings the position back to 0, the same bytes are decoded correctly this time.
8.10.5Code trace: buffer operations
The following program uses six buffer operations in turn: put, flip, get, compact, rewind, and clear.
import java.nio.ByteBuffer;
public class BufferTrace {
public static void main(String[] args) {
ByteBuffer b = ByteBuffer.allocate(8);
b.put((byte) 'J');
b.put((byte) 'A');
b.put((byte) 'V');
b.put((byte) 'A');
b.flip();
char c1 = (char) b.get();
char c2 = (char) b.get();
b.compact();
b.put((byte) '!');
b.flip();
b.get();
b.rewind();
b.clear();
System.out.println(c1 + "" + c2 + " " + b);
}
}| Step | Line | Variables | New output |
|---|---|---|---|
| 1 | 5: ByteBuffer b = ByteBuffer.allocate(8); | pos=0, lim=8, cap=8 | — |
| 2 | 6: b.put((byte) 'J'); | pos=1, lim=8, cap=8 | — |
| 3 | 7: b.put((byte) 'A'); | pos=2, lim=8, cap=8 | — |
| 4 | 8: b.put((byte) 'V'); | pos=3, lim=8, cap=8 | — |
| 5 | 9: b.put((byte) 'A'); | pos=4, lim=8, cap=8 | — |
| 6 | 10: b.flip(); | pos=0, lim=4, cap=8 | — |
| 7 | 11: char c1 = (char) b.get(); | pos=1, lim=4, cap=8, c1='J' | — |
| 8 | 12: char c2 = (char) b.get(); | pos=2, lim=4, cap=8, c1='J', c2='A' | — |
| 9 | 13: b.compact(); | pos=2, lim=8, cap=8, c1='J', c2='A' | — |
| 10 | 14: b.put((byte) '!'); | pos=3, lim=8, cap=8, c1='J', c2='A' | — |
| 11 | 15: b.flip(); | pos=0, lim=3, cap=8, c1='J', c2='A' | — |
| 12 | 16: b.get(); | pos=1, lim=3, cap=8, c1='J', c2='A' | — |
| 13 | 17: b.rewind(); | pos=0, lim=3, cap=8, c1='J', c2='A' | — |
| 14 | 18: b.clear(); | pos=0, lim=8, cap=8, c1='J', c2='A' | — |
| 15 | 19: System.out.println(c1 + "" + c2 + " " + b); | pos=0, lim=8, cap=8, c1='J', c2='A' | JA java.nio.HeapByteBuffer[pos=0 lim=8 cap=8] |
The variables in the table do not show the inside of the buffer. A tracing program that prints all eight cells of the buffer after every operation fills this gap (· is an empty cell):
allocate pos=0 lim=8 [········]
put J pos=1 lim=8 [J·······]
put A pos=2 lim=8 [JA······]
put V pos=3 lim=8 [JAV·····]
put A pos=4 lim=8 [JAVA····]
flip pos=0 lim=4 [JAVA····]
get J pos=1 lim=4 [JAVA····]
get A pos=2 lim=4 [JAVA····]
compact pos=2 lim=8 [VAVA····]
put ! pos=3 lim=8 [VA!A····]
flip pos=0 lim=3 [VA!A····]
get V pos=1 lim=3 [VA!A····]
rewind pos=0 lim=3 [VA!A····]
clear pos=0 lim=8 [VA!A····]In the first five steps, four put calls write JAVA and the position advances to 4. flip() pulls the limit down to the old position, 4, and the position becomes 0. Now only the four bytes written can be read. Two get calls read J and A; two unread bytes remain.
flip(): limit 4, position 0. (b) compact(): the unread V and A are moved to the front, position 2, limit 8. (c) clear(): position 0, limit 8; the data is not erased.compact() copies the unread V and A to the beginning of the buffer. The position is set to the number of remaining elements, 2, and the limit to the capacity, 8; the buffer switches back to write mode. One point deserves attention: the old V and A in cells 2 and 3 are not erased. The cell contents are VAVA; newly written data overwrites these old bytes. The next put('!') overwrites the old V at position 2: VA!A.
The second flip() pulls the limit down to 3; the readable data is V, A, !. One get reads V. rewind() returns the position to 0 but does not change the limit; the same data can be read again from the start. clear() sets the position to 0 and the limit to the capacity. Despite its name, it does not erase the data; the buffer is merely considered "empty" and gets overwritten. The last line shows that toString() reports the position, limit, and capacity: JA java.nio.HeapByteBuffer[pos=0 lim=8 cap=8]. Table 8.23 summarizes the operations.
| Method | What it does | Position | Limit |
|---|---|---|---|
put(x) | writes data at the position | +1 | — |
get() | reads the data at the position | +1 | — |
get(i) | reads the data at an absolute index | unchanged | — |
flip() | switches from writing to reading | 0 | old position |
rewind() | to read the same data again from the start | 0 | unchanged |
clear() | prepares for writing again; does not erase the data | 0 | capacity |
compact() | moves the unread data to the front and continues writing | number remaining | capacity |
mark() / reset() | marks the position / returns to the mark | — / mark | — |
The advantage of a buffer is that the same block of memory is used again and again. The data can be navigated and modified flexibly. The drawback is that it is complicated to use: forgetting flip is the most common mistake. The size of a buffer cannot be changed afterwards; writing past the limit throws BufferOverflowException, and reading past the limit throws BufferUnderflowException:
java.nio.HeapByteBuffer[pos=0 lim=5 cap=5]
BC then reset: pos=1 get=B
BufferOverflowException
BufferUnderflowException
java.nio.HeapIntBuffer[pos=0 lim=2 cap=3] 7 8
putInt+putShort pos=6The second line of this output shows mark and reset: the mark is set while the position is 1, and after two reads reset() brings the position back to 1. In the last line, putInt and putShort advance the position by 4 + 2 = 6. Like DataOutputStream, ByteBuffer can write primitive types in binary.
Forgetting flip(). If b.get() is called directly after b.put((byte) 'J'); b.put((byte) 'A');, the empty cell at position 2 is read and 0 is returned. What is read is not the data written but whatever lies after it. flip() is required after writing and before reading; so is clear() or compact() before writing again. There is also a type error: the put method of ByteBuffer wants a byte, and b.put('J') does not compile, because a char is not converted to a byte automatically.
8.10.6Channels
A channel is a connection that exchanges data with a file, a network socket, or another I/O device. Data from a channel is always read into a buffer (read(buffer)) and written from a buffer (write(buffer)).
put into the buffer and get from the buffer; the channel writes the buffer to a file or a socket and reads from them into the buffer.There are four basic channel types: FileChannel reads and writes files, SocketChannel transmits data over a TCP network socket, ServerSocketChannel accepts incoming TCP connections, and DatagramChannel transmits data over a UDP socket. Channels are opened with factory methods such as FileChannel.open(path, options…) and SocketChannel.open(). When the work is done, they are closed with close() or with try-with-resources.
public class ChannelOpenClose {
public static void main(String[] args) throws IOException {
// Create a FileChannel
FileChannel fileChannel = FileChannel.open(
Paths.get("file.txt"), StandardOpenOption.READ);
// Create a SocketChannel
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("example.com", 80));
System.out.println("Connected: " + socketChannel.isConnected());
// Close the channels
fileChannel.close();
socketChannel.close();
}
}Connected: trueThis program opens two channels: a file channel and a network channel connected to port 80 of example.com. In blocking mode, connect waits until the connection is established. The program was actually run for these notes, and the connection succeeded. Two close() calls keep the channels from being left open; if an exception occurs, these lines are never reached. That is why try-with-resources is safer.
Reading with a file channel follows the typical pattern of buffer use:
public class ChannelRead {
public static void main(String[] args) throws IOException {
try (FileChannel channel = FileChannel.open(
Paths.get("file.txt"), StandardOpenOption.READ)) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
// Read from the file
int bytesRead = channel.read(buffer);
System.out.println(bytesRead + " bytes read");
// Switch to read mode
buffer.flip();
// Print the data
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
}
}
}17 bytes read
NIO channel demofile.txt contains NIO channel demo and a line terminator: 16 + 1 = 17 bytes. channel.read(buffer) reads from the channel into the buffer and returns the number of bytes read; at the end of the file it returns −1. Reading is a write into the buffer; flip() is needed before reading from the buffer. In a large file a single read cannot read the whole file; the reading is then done in a loop, and at the end of each round the buffer is emptied with clear() or compact().
public class ChannelWrite {
public static void main(String[] args) throws IOException {
try (FileChannel ch = FileChannel.open(Paths.get("out.txt"),
StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
byte[] data = "Written via channel\n".getBytes(StandardCharsets.UTF_8);
ByteBuffer buf = ByteBuffer.wrap(data);
int written = ch.write(buf);
System.out.println(written + " bytes written");
}
}
}20 bytes writtenByteBuffer.wrap(data) uses a ready-made array as a buffer. The position is 0 and the limit is the size of the array; since the buffer is already in read mode, no flip() is needed. The text is 20 bytes in UTF-8: 19 characters plus the line terminator. The CREATE option creates the file if it does not exist. If the file exists and is longer, CREATE with WRITE does not shorten it; the new bytes are written at the start and the end of the old content remains. To reset the file, add TRUNCATE_EXISTING.
A file channel is two-way. The same channel can both read and write, and it can go to any position with position; in this respect it resembles RandomAccessFile:
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.*;
public class ChannelReadWrite {
public static void main(String[] args) throws IOException {
try (FileChannel ch = FileChannel.open(Path.of("both.dat"), StandardOpenOption.CREATE,
StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
ch.write(ByteBuffer.wrap("ABCDEF".getBytes()));
System.out.println("position after writing " + ch.position() + ", size " + ch.size());
ch.position(2);
ByteBuffer t = ByteBuffer.allocate(3);
int n = ch.read(t);
t.flip();
System.out.println(n + " bytes: " + new String(t.array(), 0, t.limit()));
ByteBuffer u = ByteBuffer.allocate(10);
System.out.println("next read: " + ch.read(u));
}
}
}position after writing 6, size 6
3 bytes: CDE
next read: 1A network channel works with the same pattern. The following fragment is the body of a main method: it sends an HTTP request to a web server and prints the first line of the response.
try (SocketChannel socketChannel = SocketChannel.open()) {
socketChannel.connect(new InetSocketAddress("example.com", 80));
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put(("GET / HTTP/1.1\r\nHost: example.com\r\n"
+ "Connection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII));
buffer.flip();
// Write the request to the socket
socketChannel.write(buffer);
// Read the response
buffer.clear();
socketChannel.read(buffer);
buffer.flip();
String reply = StandardCharsets.US_ASCII.decode(buffer).toString();
System.out.println(reply.substring(0, reply.indexOf("\r\n")));
} catch (IOException e) {
e.printStackTrace();
}HTTP/1.1 200 OKThe request is first put into the buffer, then flipped and written to the channel. For the response, the buffer is emptied with clear(), read from the channel, and flipped again. The Host header is mandatory in HTTP/1.1 requests. The first line of the response is HTTP/1.1 200 OK; this line is the program's real output from when these notes were prepared. A single read call may not receive the whole response. A real client keeps reading until the server closes the connection and read returns −1.
8.10.7Path and Files
The Path class of NIO.2 is the modern counterpart of File. The Files class contains static methods that reduce common file tasks to a single call.
public class FilesNio {
public static void main(String[] args) throws IOException {
Path path = Path.of("data", "grades.txt"); // Java 11+
Files.createDirectories(path.getParent());
Files.writeString(path, "Ali 70\nAyşe 85\nCan 90\n");
System.out.println(path.getFileName() + ": " + Files.exists(path));
System.out.println("Size: " + Files.size(path) + " bytes");
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println(line.toUpperCase(Locale.ROOT));
}
Files.write(path, List.of("Deniz 60"), StandardOpenOption.APPEND);
System.out.println(Files.readAllLines(path).size() + " lines");
}
}grades.txt: true
Size: 23 bytes
ALI 70
AYŞE 85
CAN 90
4 linesPath.of("data", "grades.txt") builds the path from parts and inserts the system's separator itself. createDirectories creates the directory together with any intermediate directories. writeString writes the text in UTF-8 in a single call: since the ş in Ayşe is two bytes, 22 characters take 23 bytes. readAllLines reads the whole file as a list of lines. With Files.write, the APPEND option adds a new line at the end, and the file has 4 lines.
The call toUpperCase(Locale.ROOT) in the program is deliberate. When toUpperCase() is called without a parameter, it uses the computer's locale. In the Turkish locale, the uppercase of a lowercase i is İ; on a Turkish system the program would print ALİ 70, and on an English system ALI 70. Locale.ROOT (java.util.Locale) makes the conversion language-independent, so the output is the same on every machine. This form is used for conversions that must not depend on the language, for example for file names or keywords. The difference looks like this in the Turkish locale:
tr: ALİ 70 / ROOT: ALI 70 / tıtle| Method | Purpose |
|---|---|
Path.of(…) / Paths.get(…) | creates a path (the modern counterpart of File) |
Files.readAllLines, Files.readString | reads a whole file in one call (UTF-8) |
Files.write, Files.writeString | writes in one call |
Files.exists, size, copy, move, delete | file system operations |
The methods of Files are safer than those of File in one respect: they report failure not by returning false but with a descriptive exception. If Files.delete cannot delete a non-empty directory, it throws DirectoryNotEmptyException. Because readAllLines and readString load the whole file into memory, they are meant for small and medium-sized files; very large files are read line by line with BufferedReader.
8.10.8The selector
A selector is an NIO object that watches several channels from a single thread. Channels are put into non-blocking mode and registered with the selector. select() waits until at least one channel is ready and returns the number of ready channels.
A selector is created with Selector.open(). A channel is put into non-blocking mode with configureBlocking(false) and registered with channel.register(selector, events). Which events the channel waits for is specified with SelectionKey constants (Table 8.25).
select() and handles only the ready ones.| Constant | Meaning |
|---|---|
OP_READ | the channel can be read from |
OP_WRITE | the channel can be written to |
OP_CONNECT | establishing the connection has finished |
OP_ACCEPT | a new connection can be accepted |
The following skeleton is the selector loop of a server. The loop is infinite; this program was therefore checked only by compiling it.
public class SelectorDemo {
public static void main(String[] args) throws IOException {
ServerSocketChannel server = ServerSocketChannel.open();
Selector selector = Selector.open();
server.bind(new InetSocketAddress(8080));
server.configureBlocking(false);
server.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
int ready = selector.select();
if (ready > 0) {
Set<SelectionKey> keys = selector.selectedKeys();
for (SelectionKey key : keys) {
if (key.isAcceptable()) {
// accept a connection
} else if (key.isReadable()) {
// read data
}
}
keys.clear(); // drop handled keys
}
}
}
}The server channel is bound to port 8080, put into non-blocking mode, and registered for OP_ACCEPT. In the loop, select() gives the number of ready channels and selectedKeys() gives the ready keys. If the handled keys are not removed with clear(), they come back in the next round. In a real server, the accepted client channel is also registered with OP_READ and its data is read. Two rules are checked at registration. A blocking channel cannot be registered, and a server channel supports only the OP_ACCEPT event:
registering a blocking channel: IllegalBlockingModeException
OP_READ on a server channel: IllegalArgumentException
validOps == OP_ACCEPT: true8.10.9Pros and cons of NIO
The advantages of NIO fall under three headings. Performance: data is transferred in blocks, which is more efficient than classic I/O for large files. Flexibility: buffers and channels allow flexible data handling; channels are two-way, and files and the network are processed in the same way. Many connections: with a selector, many channels are watched from a single thread, and only the active channels are processed.
The drawback is complexity. The code is longer and harder than with classic I/O. The buffer state and error cases such as a partial read or a dropped connection have to be managed by hand. Learning the selector also takes time, because the state of many channels has to be tracked correctly. As a rule, BufferedReader or Files is enough for reading a single file line by line. Channels come into their own for very large files and for large numbers of network connections.
8.11Solved problems and exercises
The numbers 12 and 345 are written first as text, then as binary. Which two numbers does the program print?
try (PrintWriter pw = new PrintWriter("s.txt")) {
pw.print(12);
pw.print(' ');
pw.print(345);
}
System.out.println(new File("s.txt").length());
try (DataOutputStream d = new DataOutputStream(new FileOutputStream("s.dat"))) {
d.writeInt(12);
d.writeInt(345);
}
System.out.println(new File("s.dat").length());PrintWriter converts the numbers to characters: "12 345", six characters. Since all the characters are ASCII, the file is 6 bytes. DataOutputStream writes two int values: 2 · 4 = 8 bytes. The output is 6 and 8. Here the text came out shorter because the numbers have few digits.
a.txt does not exist at the start. What does the program print?
try (FileWriter w = new FileWriter("a.txt")) {
w.write("ab");
}
try (FileWriter w = new FileWriter("a.txt")) {
w.write("cd");
}
try (FileWriter w = new FileWriter("a.txt", true)) {
w.write("ef");
}
try (BufferedReader r = new BufferedReader(new FileReader("a.txt"))) {
System.out.println(r.readLine());
}The first FileWriter creates the file and writes ab. The second FileWriter is not in append mode; it resets the file, ab is erased, and cd is written. The third appends with true. The file has a single line, and the output is cdef.
What does the program print on its three lines?
ByteBuffer b = ByteBuffer.allocate(10);
b.put((byte) 1).put((byte) 2).put((byte) 3);
b.flip();
b.get();
System.out.println(b.position() + " " + b.limit() + " " + b.remaining());
b.compact();
System.out.println(b.position() + " " + b.limit());
b.clear();
System.out.println(b.position() + " " + b.limit() + " " + b.get(0));After the three put calls, the position is 3. flip sets the position to 0 and the limit to 3. One get advances the position to 1; the remaining count is 3 − 1 = 2. The first line is 1 3 2. compact moves the unread 2 and 3 to the front; the position becomes the remaining count, 2, and the limit the capacity, 10. The second line is 2 10. clear sets the position to 0 and the limit to 10 but does not erase the data; get(0) gives the 2 that was moved to the front. The third line is 0 10 2.
What does the program print?
try (RandomAccessFile f = new RandomAccessFile("r.dat", "rw")) {
for (int i = 1; i <= 4; i++) f.writeInt(i * 10);
f.seek(4);
int a = f.readInt();
f.seek(f.length() - 4);
int b = f.readInt();
System.out.println(a + " " + b + " " + f.getFilePointer());
}The file has four records: 10, 20, 30, 40; each is 4 bytes, 16 bytes in all. seek(4) is the start of the second record, so a = 20. length() - 4 = 12 is the start of the last record; b = 40. After the read the pointer is at 16, that is, at the end of the file. The output is 20 40 16.
The solutions of the four exercises in the slides were also verified by running them with JDK 21. The first counts the lines, words, and characters of text.txt, whose content is "Java and files / read and write / (blank line) / very easy":
int lineCount = 0, wordCount = 0, charCount = 0;
try (BufferedReader br = new BufferedReader(new FileReader("text.txt"))) {
String line;
while ((line = br.readLine()) != null) {
lineCount++;
charCount += line.length();
String trimmed = line.trim();
if (!trimmed.isEmpty()) wordCount += trimmed.split("\\s+").length;
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
System.out.println(lineCount + " lines, " + wordCount + " words, "
+ charCount + " characters");4 lines, 8 words, 37 charactersThe trim() and isEmpty() check is needed for the blank line. "".split("\\s+") returns an array of length 1; without the check, the blank line would count as one word. The characters are 14 + 14 + 0 + 9 = 37; readLine discards the line terminators, so they are not counted.
The second exercise reads n from the keyboard, writes the numbers from 1 to n and their squares to squares.txt, then reads the file and finds the sum of the squares:
Scanner keyboard = new Scanner(System.in);
try (PrintWriter pw = new PrintWriter(new FileWriter("squares.txt"))) {
int n = keyboard.nextInt();
for (int i = 1; i <= n; i++) {
pw.println(i + " " + i * i);
}
}
int total = 0;
try (Scanner file = new Scanner(new File("squares.txt"))) {
while (file.hasNextInt()) {
file.nextInt(); // i
total += file.nextInt(); // i * i
}
}
System.out.println("Sum of squares: " + total);Sum of squares: 55Reading starts after the writing block has closed; otherwise the data would remain in the buffer and the file would be read as empty. For n = 5: 1 + 4 + 9 + 16 + 25 = 55. The third exercise serializes an int array and reads it back. Arrays are serializable:
int[] numbers = {3, 1, 4, 1, 5};
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("numbers.ser"))) {
out.writeObject(numbers);
}
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("numbers.ser"))) {
int[] loaded = (int[]) in.readObject();
int total = 0;
for (int x : loaded) total += x;
System.out.println(loaded.length + " elements, total " + total);
}5 elements, total 14In the fourth exercise, five grades are written as int values with RandomAccessFile, and the grade at a given sequence number is found without reading the whole file: f.seek((pos - 1) * 4); int grade = f.readInt();. The position of the third grade is 8. The same approach works for the last record of a log file with 10,000 lines, but only if the records have a fixed size: seek((n - 1) * size). If the lines differ in length, the position cannot be computed. Either the file is read sequentially from the start, or a \n is searched for backwards from the end.
8.12Common mistakes
The mistakes mentioned here and there in the chapter are collected below, together with the real messages of the compiler or the JVM.
Not handling a checked exception. new FileReader("a.txt") can throw FileNotFoundException, and readLine() can throw IOException. The code must be inside try-catch, or the method must say throws IOException:
Main.java:5: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
BufferedReader r = new BufferedReader(new FileReader("a.txt"));
^
Main.java:6: error: unreported exception IOException; must be caught or declared to be thrown
String s = r.readLine();
^
2 errorsForgetting the import. Scanner is in java.util, and the I/O classes are in java.io. If no import is written, the compiler cannot find the class:
Main.java:3: error: cannot find symbol
Scanner sc = new Scanner(System.in);
^
symbol: class Scanner
location: class Main
Main.java:3: error: cannot find symbol
Scanner sc = new Scanner(System.in);
^
symbol: class Scanner
location: class Main
2 errorsEach of the other mistakes was shown with its real output in the relevant section: writing a single backslash in a Windows path, not checking for null in finally, using nextLine after nextInt, not closing a buffered writer, forgetting flip() or Serializable, keeping the result of read() in a byte, and writing write(chunk) in a block copy. In most of these the program compiles and runs but gives a wrong result. For this reason, after writing I/O code, always check the size of the copy, the values read, and the actual contents of the file.
8.13Summary
- A stream is a structure that carries data from a source to a destination in order. Every Java program has three standard streams:
System.in,System.out, andSystem.err. When output is redirected,System.errstays on the screen. Scannerreads the keyboard, files, and strings.nextInt()leaves the line terminator in the buffer; a followingnextLine()returns an empty string.- Every file is a sequence of bytes. In a text file the bytes are converted to letters with a character encoding; in a binary file they are interpreted as numbers, pixels, or instructions.
- ASCII is 7 bits, and ISO-8859-9 is 8 bits for Turkish; UTF-8 writes a character with 1–4 bytes and has been the default since Java 18. A file must be read with the encoding it was written in.
- 127 is 3 bytes as text and 4 bytes as an
int. The binary size depends on the type, the text size on the number of digits. Binary data is read back in the order and with the type in which it was written. Fileis only a path; it does not read the contents. Most of its methods report errors by returningfalse.- Byte streams (
InputStream/OutputStream) are for any kind of data, and character streams (Reader/Writer) are for text. Wrapper streams add capabilities; closing the outermost one closes them all. readLine()returnsnullat the end of the file, andread()returns −1. The result ofread()is kept in anint.FileWriter(name, true)appends; the form without the parameter resets the file.PrintWriterdoes not throw exceptions; errors are seen withcheckError().- Buffering batches disk accesses. Data written may wait in memory until
flush()orclose(). - try-with-resources closes resources in the reverse of the opening order and before
catch. - In a block copy, only the
nbytes actually read are written:write(chunk, 0, n). The shortcuts aretransferToandFiles.copy. RandomAccessFilejumps to any position withseek; with fixed-size records, the position of record k is k · record size.- Serialization converts an object to bytes. The class implements
Serializable;staticandtransientfields are not written; the constructor is not called on reading back. - NIO works with buffers, channels, and selectors. After writing to a buffer, call
flip()before reading andclear()orcompact()before writing again.
8.14Key terms
- stream
- standard input / output
- text file / binary file
- character encoding
- byte stream / character stream
- wrapper stream (decorator)
- buffer / buffering
- try-with-resources
- checked exception
- random access file
- serialization
- channel
- selector
- locale
- thread
8.15Test Yourself
How many bytes does the word
"Ilık"take in UTF-8 and in ISO-8859-9?Answer
In UTF-8,
I,l, andktake one byte each andıtakes two: 5. In ISO-8859-9 every letter is one byte: 4.With a
PrintWriter,print(5L),print('A'), andprint(1.5f)are called; with aDataOutputStream,writeLong(5),writeChar('A'), andwriteFloat(1.5f). How many bytes is each of the two files?Answer
The text file contains
5A1.5: 5 bytes. In the binary file,longis 8,char2, andfloat4 bytes: 14 bytes.print(1.5f)is independent of the locale and writes a dot.A file of 10,000 bytes is read by calling
read(array)with a 4096-byte array. What values do the calls return? Ifwrite(array)had been used in the copy, how many bytes would the copy have?Answer
4096, 4096, 1808, and −1 at the end of the file.
write(array)writes the whole array in every round: 3 · 4096 = 12,288 bytes. In the last round, 2288 stale bytes are written in addition.ByteBuffer t = ByteBuffer.allocate(5);then 1, 2, 3 are written withput; thenflip(), twoget()calls,compact(),put((byte) 9), andflip()again. What are the position, the limit, the remaining count, and cells 0 and 1?Answer
After the two
getcalls, the only unread element is 3.compactmoves it to the front: position 1, limit 5.put(9)writes to cell 1 and the position becomes 2.flipsets the limit to 2 and the position to 0. Result: position 0, limit 2, remaining 2, cells 3 and 9.Into an empty file, 7, 8, 9 are written as
intvalues withRandomAccessFile. Thenseek(4); writeInt(100); seek(length()); writeShort(1);is done. What is the length of the file, and what doesreadShort()return afterseek(0)?Answer
Three
intvalues are 12 bytes;writeInt(100)is written in place of the 8, and the length does not change.writeShortappends 2 bytes at the end: 14.readShort()reads the first two bytes. Since the bytes of 7 are00 00 00 07, the result is 0.An object is created of a serializable class whose constructor prints "constructed" and which has the fields
transient String note = "temporary";andint n = 5;;nis set to 8, and the object is written and read back. How many times is "constructed" printed, and what arenoteandnin the object read?Answer
Once;
readObjectdoes not call the constructor.noteisnull, because atransientfield is not written and its field initializer does not run either.nis 8.The block
try (R a = new R("A"); R b = new R("B"); R c = new R("C")) { … }finishes without an exception;Rprints a message when it is opened and when it is closed. What is the order of the messages?Answer
A opened, B opened, C opened, the body, C closed, B closed, A closed. Resources are opened from left to right and closed in the reverse order.
A 3 MB file is read byte by byte through a default
BufferedInputStream. How many reads are made on the underlyingFileInputStream?Answer
3 · 1,048,576 / 8192 = 384 reads that carry data, plus one read for the end of the file: 385.
8.16Further reading
- Oracle, The Java Tutorials, "Basic I/O": the official, free source that explains streams,
Scannerand formatting, and file operations with NIO.2 through short examples. - C. S. Horstmann, Core Java, Volume II: Advanced Features (12th ed.), Chapter 2 "Input and Output": treats stream classes, character encodings, serialization, and memory-mapped files in detail.
- Oracle, Java Object Serialization Specification: defines the format of serialized bytes, how
serialVersionUIDis computed, and the rules of version compatibility. - OpenJDK, JEP 400 "UTF-8 by Default": explains why the default encoding was made UTF-8 in Java 18 and what the effect on older programs is.
8.17References
- Oracle, The Java Tutorials: "Basic I/O" (I/O Streams, File I/O featuring NIO.2), "Scanning and Formatting".
- Oracle, Java SE 21 API Documentation: the packages
java.io,java.nio,java.nio.channels, andjava.nio.file. - Oracle, Java Object Serialization Specification.
- J. Gosling et al., The Java Language Specification, Java SE 21 Edition (3.10.6 escape sequences, 14.20.3 try-with-resources).
- P. Deitel and H. Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2017 (Chapter 15: Files, Input/Output Streams, NIO and XML Serialization).
- C. S. Horstmann, Core Java, Volume II: Advanced Features, 12th ed., 2022 (Chapter 2: Input and Output).
- K. Sierra and B. Bates, Head First Java, 3rd ed., O'Reilly, 2022 (Chapter 16: Saving Objects (and Text)).
- A. B. Downey and C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019.
- OpenJDK, JEP 400: UTF-8 by Default, JDK 18, 2022. https://openjdk.org/jeps/400
Related pages: Chapter 8 slides · Study questions · Glossary · © Sercan Külcü. All rights reserved.