In DataDemo, the program writes writeInt(100), writeDouble(2.5), writeBoolean(true), writeChar('A') and writeUTF("KSHB"). What does out.size() report, what is printed after reading back, and what happens on the extra readInt()?
java.io models every input and output as a stream: byte streams (InputStream/OutputStream) for binary data and character streams (Reader/Writer) for text, combined like building blocks. Covers buffering, data and object streams, serialization, the File class, RandomAccessFile, System.in/out/err and NIO.
new BufferedReader(new InputStreamReader(System.in)).A stream is an ordered sequence of data flowing from a source to a destination. An input stream brings data into the program; an output stream sends data out. The beauty of the idea is uniformity: the same read() and write() calls work whether the other end is a file, the keyboard, a network socket, a byte array in memory or another thread.
| Input (read) | Output (write) | |
|---|---|---|
| Bytes — 8-bit, binary data | InputStream: int read(), read(byte[]), skip(), available(), close() | OutputStream: write(int), write(byte[]), flush(), close() |
| Characters — 16-bit Unicode text | Reader: int read(), read(char[]), close() | Writer: write(int), write(String), flush(), close() |
Use byte streams for images, audio, compressed files and serialized objects — anything that is not text. Use character streams for text: they translate between bytes and characters using a charset (character encoding). They arrived in JDK 1.1 so that Java programs could handle every language correctly; since Java 18 the default charset is UTF-8 on every platform (before that it depended on the operating system).
read() returns an int — 0–255 for a byte, 0–65535 for a char — or −1 at the end of the data.flush() pushes buffered output to its destination; close() flushes and releases the resource; closing a wrapper closes the stream it wraps.| Class | Role |
|---|---|
| FileInputStream / FileOutputStream | Read / write the bytes of a file; new FileOutputStream(name, true) appends |
| ByteArrayInputStream / ByteArrayOutputStream | Use a byte[] in memory as the source / a growable destination (toByteArray()) |
| BufferedInputStream / BufferedOutputStream | Add a buffer (8 KB by default) so the device is touched far less often |
| DataInputStream / DataOutputStream | Read / write Java primitives in a portable binary format |
| ObjectInputStream / ObjectOutputStream | Read / write whole objects (serialization) |
| PrintStream | print(), println(), printf() for any value; it never throws IOException — call checkError() |
| PipedInputStream / PipedOutputStream | A pipe between two threads |
| SequenceInputStream, PushbackInputStream | Read several streams one after another / push bytes back with unread() |
import java.io.*;
public class Bytes {
public static void main(String[] args) throws IOException {
ByteArrayOutputStream mem = new ByteArrayOutputStream(); // a growable byte[] sink
try (BufferedOutputStream out = new BufferedOutputStream(mem)) {
for (int b = 65; b <= 70; b++) out.write(b); // the bytes of 'A' .. 'F'
} // close() flushes the buffer
byte[] data = mem.toByteArray();
System.out.println(data.length + " bytes: " + new String(data, "US-ASCII"));
try (InputStream in = new ByteArrayInputStream(data)) {
int b, sum = 0;
while ((b = in.read()) != -1) sum += b; // -1 marks the end
System.out.println("sum " + sum); // 65 + 66 + ... + 70
}
}
}Writing the number 100000 as text takes six characters and must be parsed back. DataOutputStream instead writes each primitive in a fixed-size binary form (big-endian, identical on every platform), and DataInputStream reads it back. The reader must use the same methods in the same order as the writer, and reading past the end throws EOFException rather than returning −1.
| Methods | Bytes on the stream |
|---|---|
| writeBoolean / readBoolean, writeByte / readByte | 1 |
| writeShort / readShort, writeChar / readChar | 2 |
| writeInt / readInt, writeFloat / readFloat | 4 |
| writeLong / readLong, writeDouble / readDouble | 8 |
| writeUTF(s) / readUTF() | 2-byte length + the characters in modified UTF-8 (1 byte each for plain ASCII) |
| writeChars(s) | 2 per character, with no length prefix |
| size() (DataOutputStream) | Total bytes written so far |
import java.io.*;
public class DataDemo {
public static void main(String[] args) throws IOException {
try (DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream("rec.dat")))) {
out.writeInt(100); // 4 bytes
out.writeDouble(2.5); // 8 bytes
out.writeBoolean(true); // 1 byte
out.writeChar('A'); // 2 bytes
out.writeUTF("KSHB"); // 2 + 4 = 6 bytes
System.out.println("written: " + out.size() + " bytes");
}
try (DataInputStream in = new DataInputStream(
new BufferedInputStream(new FileInputStream("rec.dat")))) {
int i = in.readInt(); // read back in the SAME order
double d = in.readDouble();
boolean b = in.readBoolean();
char c = in.readChar();
String s = in.readUTF();
System.out.println(i + " " + d + " " + b + " " + c + " " + s);
in.readInt(); // nothing left: EOFException
} catch (EOFException e) {
System.out.println("end of file reached");
}
}
}| Class | Role |
|---|---|
| FileReader / FileWriter | Characters from / to a file; FileWriter(name, true) appends; a Charset argument is accepted since Java 11 |
| BufferedReader / BufferedWriter | Buffering; readLine() returns a line without its terminator, or null at the end; newLine() writes a line separator |
| InputStreamReader / OutputStreamWriter | The bridges: decode bytes into chars / encode chars into bytes, with a chosen charset |
| PrintWriter | print(), println(), printf() for text, with optional autoflush on println |
| StringReader / StringWriter, CharArrayReader / CharArrayWriter | Use strings and char arrays in memory as sources and destinations |
| LineNumberReader | A BufferedReader that also counts lines |
| PushbackReader, PipedReader / PipedWriter | Push characters back; connect two threads |
FileReader is simply an InputStreamReader attached to a FileInputStream (it extends InputStreamReader), and FileWriter extends OutputStreamWriter. When the encoding matters — Malayalam text in a UTF-8 file, say — build the bridge yourself: new InputStreamReader(new FileInputStream(f), StandardCharsets.UTF_8). Decoding with the wrong charset turns every non-ASCII character into garbage.
The standard streams are fields of System: System.in is an InputStream connected to the keyboard; System.out is a PrintStream for normal output; System.err is a separate PrintStream for error messages, so the shell can redirect it independently (2> errors.txt). They can be replaced with System.setIn/setOut/setErr. Scanner and System.console() (with readPassword()) are convenient alternatives for console input.
import java.io.*;
public class ReadName {
public static void main(String[] args) throws IOException {
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Name: ");
String name = kb.readLine(); // a whole line, without the newline
System.out.print("Age: ");
int age = Integer.parseInt(kb.readLine().trim());
System.out.println(name + " will be " + (age + 1) + " next year");
System.err.println("(diagnostics go to standard error)");
}
}java.io.File is an abstract representation of a file or directory path. It never opens or reads anything, and creating a File object does not create a file on disk — it only names one. Its methods query and manipulate the file system entry the path refers to.
| Method | Returns |
|---|---|
| getName() | "june.txt" |
| getParent() | "reports" |
| getPath() / getAbsolutePath() | "reports/june.txt" as given / the full path from the root |
| exists() / isFile() / isDirectory() | true / true / false |
| length() | 1200 (bytes) — and 0 if the file does not exist |
| canRead() / canWrite() / isHidden() / lastModified() | Permission and attribute checks; time in ms since 1 Jan 1970 |
| createNewFile() | true if it created the file, false if it already existed |
| mkdir() / mkdirs() | Create one directory / every missing directory on the path |
| delete() | true if deleted — a directory must be empty |
| renameTo(File dest) | true on success |
| list() / listFiles() | Names (String[]) / File objects (File[]) in a directory; null if it is not a directory |
| File.separator / File.pathSeparator | '/' and ':' on Linux and macOS; '\' and ';' on Windows |
import java.io.File;
import java.io.IOException;
public class FileInfo {
public static void main(String[] args) throws IOException {
File dir = new File("reports");
System.out.println(dir.exists()); // false the first time
System.out.println(dir.mkdir()); // true: directory created
File f = new File(dir, "june.txt"); // parent + child
System.out.println(f.exists() + " " + f.length()); // false 0 (only a path so far)
System.out.println(f.createNewFile()); // true: an empty file now exists
System.out.println(f.isFile() + " " + f.getName() + " " + f.getParent()); // true june.txt reports
System.out.println(dir.list().length); // 1
System.out.println(dir.delete()); // false: the directory is not empty
System.out.println(f.delete() + " " + dir.delete()); // true true
}
}RandomAccessFile treats a file like a large byte array with a movable file pointer. It is not part of the InputStream/OutputStream hierarchy; it implements both DataInput and DataOutput, so it has readInt(), writeDouble(), readUTF() and the rest. Open it in mode "r" (read-only) or "rw" (read-write; "rws" and "rwd" also force updates to disk). seek(pos) moves the pointer, getFilePointer() reports it, length() and setLength() give and change the size — ideal for fixed-length records.
import java.io.IOException;
import java.io.RandomAccessFile;
public class Records {
public static void main(String[] args) throws IOException {
try (RandomAccessFile raf = new RandomAccessFile("marks.dat", "rw")) {
raf.setLength(0); // start with an empty file
int[] marks = {78, 91, 85, 66};
for (int m : marks) raf.writeInt(m); // 4 records x 4 bytes
System.out.println(raf.length()); // 16
raf.seek(2 * 4); // jump to record 3 (index 2)
System.out.println(raf.readInt()); // 85
raf.seek(2 * 4);
raf.writeInt(95); // overwrite record 3 in place
raf.seek(0);
int sum = 0;
for (int i = 0; i < 4; i++) sum += raf.readInt();
System.out.println(sum + " " + raf.getFilePointer()); // 330 16
}
}
}Serialization converts an object's state into a stream of bytes — to save it in a file, send it over a network or cache it — and deserialization rebuilds the object from those bytes. ObjectOutputStream.writeObject(obj) writes the object together with every object it refers to (the whole object graph, with shared references and cycles preserved); ObjectInputStream.readObject() returns an Object that you cast back.
java.io.Serializable, a marker interface with no methods; otherwise writeObject throws NotSerializableException. Every object reachable from it must be serializable too.transient fields are skipped and come back with default values (0, false, null) — use it for passwords, caches, open connections.static fields belong to the class, not the object, so they are never written; after reading you see the class's current static value.serialVersionUID (private static final long serialVersionUID = 1L;) stamps the class version; if the stored stamp differs from the loaded class's, readObject throws InvalidClassException. Without an explicit value the JVM computes one from the class's structure, so a harmless edit can break old files.Externalizable gives full manual control.import java.io.*;
class Employee implements Serializable {
private static final long serialVersionUID = 1L;
static String org = "KSHB"; // static: not part of the saved object
String name;
int id;
transient String password; // transient: deliberately not saved
Employee(String name, int id, String password) {
this.name = name; this.id = id; this.password = password;
}
}
public class SerialDemo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("emp.ser"))) {
out.writeObject(new Employee("Anu", 7, "secret"));
}
Employee.org = "Housing Board"; // change the static AFTER saving
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("emp.ser"))) {
Employee e = (Employee) in.readObject(); // returns Object: cast it
System.out.println(e.name + " " + e.id + " " + e.password + " " + Employee.org);
}
}
}Rather than one class for every combination of features (a 'buffered data file input stream'…), java.io provides small classes that each add one feature and take another stream in their constructor. You stack them in whatever combination you need — the decorator (wrapper) pattern. FilterInputStream, FilterOutputStream, FilterReader and FilterWriter are the decorator base classes.
| Layer | What it adds |
|---|---|
| FileInputStream (innermost) | The real source: raw bytes from the file |
| BufferedInputStream | Fetches 8 KB at a time and serves later reads from memory |
| DataInputStream (outermost) | readInt(), readDouble(), readUTF() on top of plain bytes |
new DataInputStream(new BufferedInputStream(new FileInputStream("rec.dat"))) from the inside outThe program talks only to the outermost object, and closing it closes the whole chain. Put the buffer next to the real device, and the 'interpreting' layer (Data, Object, Reader) outside it.
import java.nio.file.*;
import java.util.List;
Path p = Paths.get("notes.txt"); // Path.of("notes.txt") in Java 11+
Files.write(p, List.of("line 1", "line 2")); // create or overwrite, UTF-8
List<String> lines = Files.readAllLines(p); // [line 1, line 2]
long size = Files.size(p); // size in bytes
Files.copy(p, Paths.get("notes.bak"), StandardCopyOption.REPLACE_EXISTING);
Files.delete(Paths.get("notes.bak"));Try the problem first, then reveal the working one step at a time.
In DataDemo, the program writes writeInt(100), writeDouble(2.5), writeBoolean(true), writeChar('A') and writeUTF("KSHB"). What does out.size() report, what is printed after reading back, and what happens on the extra readInt()?
Predict the output of SerialDemo: an Employee("Anu", 7, "secret") with transient password and static org = "KSHB" is written; then org is changed to "Housing Board"; then the object is read back and name, id, password and org are printed.
A UTF-8 text file containing Malayalam must be read line by line on any Java version. Build the stream chain, explain each layer, and say why plain new FileReader("data.txt") might fail on older JDKs.
Run FileInfo in a folder where no 'reports' directory exists. Give each printed result and explain the two calls to dir.delete().
How many bytes are written by out.writeInt(5); out.writeLong(5L); out.writeShort(5); out.writeUTF("Hi!"); out.writeBoolean(false); on a DataOutputStream?
Choose the class (or chain) for: (a) reading a UTF-8 text file line by line; (b) storing 1,000 doubles compactly and reading them back; (c) saving a whole object to disk; (d) changing the 50th fixed-size record of a file in place; (e) writing formatted report lines to a text file; (f) listing the files in a folder.
A Serializable class has fields int count = 5; (transient), String city = "Kochi"; and Thread worker; (a non-null Thread object). What happens when such an object is written and read back?
Why does InputStream.read() return an int instead of a byte? What goes wrong with byte b; while ((b = (byte) in.read()) != -1) { … } on a file that contains the byte 0xFF?
A RandomAccessFile holds int records (4 bytes each). Where does the 6th record start? What does getFilePointer() return after you seek there and call readInt()? What is length() for 10 records?
new File("x.txt") does not create a file; length() returns 0 for a missing file; delete() returns false for a non-empty directory.10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.