Chapter 8: Input and Output
Multiple Choice · Streams
Question 1: Redirecting Output to a File
The program calls both System.out.println("result") and System.err.println("warning") and is launched from the command line with java App > result.txt. Which statement is true?
C: The > operator redirects only standard output (System.out) to the file. System.err is a separate stream and stays on the screen, so error messages do not get mixed into the output file and are not missed.
Output Question · Streams
Question 2: nextLine After nextInt
Instead of keyboard input, a Scanner reading the same text is used. What does the program print?
Scanner sc = new Scanner("19\nAyşe Yılmaz\n");
int age = sc.nextInt();
String name = sc.nextLine();
System.out.println("[" + name + "] " + age);
System.out.println("[" + sc.nextLine() + "]");Show answer
[] 19 [Ayşe Yılmaz]
nextInt() reads only the digits 19. The line break (⏎) is left unread. The first nextLine() returns the empty text up to that line break: name = "". The actual name comes from the second nextLine().
Fix: after nextInt(), call sc.nextLine(); to discard the line break, or read the number with Integer.parseInt(sc.nextLine()).
Multiple Choice · Files and Encoding
Question 3: How Many Bytes?
"Çağrı" (5 characters) is written to a text file using UTF-8 encoding. How many bytes is the file?
B: UTF-8 writes ASCII characters (a, r) in 1 byte and Turkish letters (Ç, ğ, ı) in 2 bytes: 2 + 1 + 2 + 1 + 2 = 8. 5 bytes is the size of a file saved with ISO-8859-9 (Latin-5), and 10 bytes the size with BOM-less UTF-16 (e.g. UTF-16BE). "Çağrı".getBytes(StandardCharsets.UTF_8).length also gives 8.
Output Question · Files and Encoding
Question 4: Text vs. Binary Size
The same values are written first as text, then as binary. Which two numbers does the program print?
try (PrintWriter pw = new PrintWriter("m.txt")) { pw.print(-15); pw.print(3.5); } System.out.println(new File("m.txt").length()); try (DataOutputStream d = new DataOutputStream( new FileOutputStream("m.dat"))) { d.writeShort(-15); d.writeDouble(3.5); d.writeBoolean(true); } System.out.println(new File("m.dat").length());
Show answer
6 11
Text: print(-15) and print(3.5) write their characters side by side: "-153.5", 6 characters, 6 bytes in ASCII.
Binary: writeShort writes 2, writeDouble writes 8, writeBoolean writes 1 byte: 2 + 8 + 1 = 11. In a binary file the size depends on the type of the value, not on its number of digits; but the values are read back correctly only in the same order (readShort, readDouble, readBoolean).
Multiple Choice · File System
Question 5: File for a Missing File
With no file named missing.txt on disk, File f = new File("missing.txt"); is executed. Which statement is true?
D: File only represents a path; it does not touch the disk and throws no exception. For a missing file, exists() returns false and length() returns 0. Creating a file takes createNewFile() or a write stream; FileNotFoundException comes when a stream is opened to read the file (new FileReader(f)).
Output Question · Reading and Writing Text
Question 6: Writing, Appending, Counting Lines
g.txt does not exist at first. What does the program print?
try (FileWriter w = new FileWriter("g.txt")) { w.write("one\ntwo\n"); } try (FileWriter w = new FileWriter("g.txt", true)) { w.write("three"); } try (FileWriter w = new FileWriter("g.txt", true)) { w.write("four\n"); } int n = 0; String last = null; try (BufferedReader r = new BufferedReader( new FileReader("g.txt"))) { String s; while ((s = r.readLine()) != null) { n++; last = s; } } System.out.println(n + " " + last);
Show answer
3 threefour
The first writer creates the file: one⏎two⏎. The second and third use true to append; "three" contains no line break, so "four" sticks to the same line: one⏎two⏎threefour⏎.
readLine() reads three lines, discarding the line breaks; the fourth call returns null. Without true, each writer would reset the file.
Coding Question · Reading and Writing Text
Question 7: Processing a Grades File
grades.txt has a name and an integer grade on each line (e.g. Ali 70, Ayşe 85, Can 90). Write code that reads the file with Scanner and prints the number of people and the average grade; if the file is missing, print an error message, and make sure the Scanner is closed in every case.
Show answer
int total = 0, count = 0; try (Scanner f = new Scanner(new File("grades.txt"))) { while (f.hasNext()) { f.next(); // name total += f.nextInt(); // grade count++; } System.out.println(count + " people, average " + (double) toplam / adet); } catch (FileNotFoundException e) { System.err.println("File not found: " + e.getMessage()); }
Output for the sample file: 3 people, average 81.66666666666667. try-with-resources closes the Scanner even if an error occurs; the (double) cast prevents integer division. next() reads one word up to whitespace, nextInt() reads a number.
Multiple Choice · Buffering
Question 8: How Many Times Does the Buffer Fill?
A 2 MB (2,097,152 bytes) file is read byte by byte using new BufferedInputStream(new FileInputStream(f)) and calling read(). The buffer is 8192 bytes. The data reaches the underlying FileInputStream in how many read calls?
A: Each time the buffer empties it asks the underlying stream for 8192 bytes at once: 2,097,152 / 8192 = 256 data-carrying reads (plus a final call that returns −1). The program's 2,097,152 read() calls are served from the in-memory buffer. In an unbuffered stream each read() would be a system call.
Multiple Choice · Other Byte Streams
Question 9: Storing read() in a byte
How many bytes does this loop process?
InputStream in = new ByteArrayInputStream( new byte[] {65, (byte) 255, 66}); byte b; int processed = 0; while ((b = (byte) in.read()) != -1) { processed++; } System.out.println(processed);
B: The first byte, 65, is processed. The second read() returns 255; (byte) turns it into −1 and the loop stops, taking it for end of file. The third byte is never read. That is why the result of read() is stored in an int variable: data is 0–255 and end of file is −1, so they stay distinguishable.
Step-by-Step Trace · Other Byte Streams
Question 10: read(byte[]) and Stale Bytes
A 7-byte in-memory source is read with a 3-byte array. What does the program print?
The source has 7 bytes: J, A, V, A, -, I, O. The stream will be read from the start.
The 3-cell array is created filled with zeros.
read(buf) reads at most 3 bytes: J, A, V. The returned value is 3.
new String(buf) converts the whole array: JAV.
The next 3 bytes overwrite the same array: A, -, I.
Second line: A-I.
Only 1 byte is left: buf[0] = O; buf[1] and buf[2] are - and I, left over from the previous round.
The bug shows: although k = 1, 3 bytes were converted and O-I was printed. Correct is new String(buf, 0, k): only O.
The source is exhausted: read returns −1 and the loop ends. The same mistake in a copy, write(buf), would grow the copy; write(buf, 0, k) is needed.
byte[] source = "JAVA-IO".getBytes(); InputStream in = new ByteArrayInputStream(source); byte[] buf = new byte[3]; int k; while ((k = in.read(buf)) != -1) { System.out.println(k + " " + new String(buf)); }
Multiple Choice · File Copying
Question 11: When the Target File Already Exists
k2.txt already exists, Files.copy(Paths.get("k1.txt"), Paths.get("k2.txt")); is called. What happens?
C: Files.copy does not overwrite an existing target by itself; it throws java.nio.file.FileAlreadyExistsException: k2.txt. To overwrite, give the third argument StandardCopyOption.REPLACE_EXISTING. Appending is done with FileWriter(name, true) or StandardOpenOption.APPEND.
Coding Question · File Copying
Question 12: A Block-by-Block Copy Method
static long copy(String source, String target) throws IOException — write this method: it copies any kind of file in 4 KB chunks using buffered streams, closes the streams in every case and returns the number of bytes copied.
Show answer
static long copy(String source, String target) throws IOException { byte[] chunk = new byte[4096]; long total = 0; try (InputStream in = new BufferedInputStream( new FileInputStream(source)); OutputStream out = new BufferedOutputStream( new FileOutputStream(target))) { int n; while ((n = in.read(chunk)) != -1) { out.write(chunk, 0, n); // only the n bytes read total += n; } } return total; }
Tested with a random 10,000-byte file: 10000 was returned and the copy was identical byte by byte. Because byte streams are used, binary files such as images and .class files are not corrupted either; a character stream (FileReader) can corrupt binary data. The resources are closed in reverse order; out flushes its buffer to disk when it is closed.
Step-by-Step Trace · Random Access
Question 13: Records with RandomAccessFile
r.dat does not exist at first. Each int is 4 bytes. What does the program print?
"rw": the file is created if it does not exist; the pointer is at 0.
Four writeInt calls: 5, 10, 15, 20. Each writes 4 bytes, advancing the pointer to 16.
seek(8): the start of record 3. readInt reads bytes 8–11: 15; the pointer is 12.
The value read and the pointer are printed.
seek(4) and writeInt(99): record 2 is changed in place (10 → 99); the rest of the file stays the same.
seek(length()) goes to the end of the file; writeInt(25) grows the file to 20 bytes.
Length is 20, and the pointer is 20 too (end of file).
Go back to the start; read five ints until the pointer reaches the length: 5 + 99 + 15 + 20 + 25 = 164.
The total is printed and the file is closed. Replacing record 2 in place was impossible with streams.
RandomAccessFile f = new RandomAccessFile("r.dat", "rw"); for (int i = 1; i <= 4; i++) f.writeInt(i * 5); f.seek(8); int x = f.readInt(); System.out.println(x + " " + f.getFilePointer()); f.seek(4); f.writeInt(99); f.seek(f.length()); f.writeInt(25); System.out.println(f.length() + " " + f.getFilePointer()); f.seek(0); int t = 0; while (f.getFilePointer() < f.length()) t += f.readInt(); System.out.println("Total: " + t); f.close();
Multiple Choice · Serialization
Question 14: A Non-Serializable Field
Student class implements Serializable, but Address does not. What happens when out.writeObject(new Student()) runs?
class Address {
String city = "Giresun";
}
class Student implements Serializable {
String name = "Ece";
Address address = new Address();
}D: Serialization also writes the objects that the fields refer to; Address does not carry the marker interface, so java.io.NotSerializableException is thrown at run time. The compiler does not check this. Fix: make Address implement Serializable too, or mark the field transient (it is then null after reading back).
Output Question · Serialization
Question 15: transient, static and a New Object
P object is written and read back. What does the last line print?
class P implements Serializable { int a = 1; transient int b = 2; static int c = 3; } // inside main: P p = new P(); p.a = 10; p.b = 20; P.c = 30; ObjectOutputStream o = new ObjectOutputStream( new FileOutputStream("p.ser")); o.writeObject(p); o.close(); P.c = 40; ObjectInputStream i = new ObjectInputStream( new FileInputStream("p.ser")); P q = (P) i.readObject(); i.close(); System.out.println(q.a + " " + q.b + " " + P.c + " " + (q == p));
Show answer
10 0 40 false
awas serialized: 10.btransient: not written; after reading back it has the default value 0. The field initializer (= 2) does not run, becausereadObjectdoes not call the constructor of a serializable class.cstatic: belongs to the class, not the object, and is never written to the file; the last in-memory value is 40.readObjectbuilds a new object:q == pis false.
Multiple Choice · NIO
Question 16: What Is a Selector For?
Which statement is true for the NIO selector (Selector)?
A: Channels are put in non-blocking mode with configureBlocking(false) and registered with calls such as register(selector, SelectionKey.OP_READ); select() blocks until at least one channel is ready. This way many connections are handled with one thread; one thread per connection is the classic stream model. flip() is a buffer operation.
Step-by-Step Trace · NIO
Question 17: ByteBuffer: flip and compact
These operations are performed on a 6-byte buffer. What does the program print? Green cells lie between the position (pos) and the limit (lim).
Empty buffer: in write mode the position is 0, limit = capacity = 6.
Four put calls: 10, 20, 30, 40. Each put advances the position by 1: pos 4.
flip(): limit = old position (4), position = 0. Readable data is 0–3.
Two get calls: 10 and 20. The unread 30 and 40 remain.
compact(): the unread 30, 40 are copied to the start; pos = number remaining (2), lim = 6. The old 30, 40 at 2–3 are not erased, they will be overwritten.
50 and 60 are written at positions 2 and 3.
Back to read mode: lim 4, pos 0. To be read: 30, 40, 50, 60.
remaining() = lim − pos = 4.
get() reads the one at the position (30) and advances pos; get(3) reads by absolute index (60) and leaves pos alone.
ByteBuffer b = ByteBuffer.allocate(6); b.put((byte) 10).put((byte) 20); b.put((byte) 30).put((byte) 40); b.flip(); byte g1 = b.get(); byte g2 = b.get(); b.compact(); b.put((byte) 50).put((byte) 60); b.flip(); System.out.println(g1 + " " + g2); System.out.println(b.position() + " " + b.limit() + " " + b.remaining()); System.out.println(b.get() + " " + b.get(3));