Chapter 8: Input and Output
Introduction
Learning Outcomes
Describe input/output streams and System.in, System.out, System.err; read the keyboard with Scanner.
Distinguish text and binary files, the ASCII, ISO-8859-9 and UTF-8 encodings, and work out how many bytes a number takes in a file.
Process text files with File, Scanner, BufferedReader, PrintWriter, FileWriter; close resources with try-with-resources.
Tell byte streams (InputStream/OutputStream) from character streams (Reader/Writer), and buffered from wrapper streams.
Copy byte by byte, by block and by line; jump to any position with RandomAccessFile.
Serialize objects (Serializable, transient); explain what NIO buffers, channels and selectors are for.
Streams
Streams
- A stream carries data from a source to a destination in order, piece by piece. The data may be characters, numbers or raw bytes.
- Input stream: data flows into the program. Example:
System.in(keyboard). - Output stream: data flows out of the program. Example:
System.out(screen). - Think of a water pipe: water leaves the far end in the order it went in, and the program doesn't care whether a tap or a tank sits at the other end.
Keyboard, file or network: the program uses the same read() / write() methods. That shared interface is the strength of Java's I/O library.
Streams
Keyboard and Screen: Standard Streams
- Transient data: keyboard and screen data is not stored; it is gone when the program ends.
- Live flow: input arrives as the user types; output appears as the program writes.
- Every Java program starts with three ready-made streams:
| Stream | Java object | Type |
|---|---|---|
| standard input | System.in | InputStream |
| standard output | System.out | PrintStream |
| standard error | System.err | PrintStream |
System.err also writes to the screen, but on a separate channel: even when output is redirected to a file (java App > out.txt), error messages stay on screen.Streams
First Example: Reading and Writing
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."); } }
42 Hello, World! You entered: 42 This line went to stderr.
new Scanner(System.in)creates a scanner that reads the keyboard stream.Scannerlives injava.util, so theimportis required.nextInt()blocks until the user types a number and presses Enter.System.out.printlnwrites a line to the output stream.System.err.printlnwrites to the error stream; most IDEs show it in red.- If the user types
abcinstead of a number, anInputMismatchExceptionis thrown.
Streams
Reading the Keyboard with Scanner, Step by Step
The Scanner is attached to System.in. The keyboard buffer is empty.
print (not println) shows the prompt, so the user answers on the same line.
The user types Ayşe Yılmaz and presses Enter. nextLine() takes the whole line, spaces included, and drops the newline (⏎).
The second prompt is printed.
nextInt() reads the digits and converts them to the int 19. The newline (⏎) stays in the buffer.
The value is now an ordinary int: 19 + 1 = 20.
Lines are written to the output stream.
String concatenation: "Next year you'll be " + 20 + ".".
close() closes System.in along with the scanner; the program can no longer read the keyboard.
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(); } }
Files and Encoding
Files
- A file stores data persistently on disk: it survives the program exiting and the computer restarting (variables in RAM do not).
- Every file is ultimately 0s and 1s, a sequence of bytes. What differs is how those bytes are interpreted.
- Text files: bytes are turned into letters by a character encoding; people can read them.
- Binary files: bytes are numbers, pixels, audio samples, machine instructions; only a program that knows the format can make sense of them.
file.txt 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!
Offset on the left, each byte in hex in the middle, the ASCII view on the right. 4D = 77 = M. The 15 characters (Turkish for “Hello, world!”) take 16 bytes: ü is two bytes in UTF-8 (C3 BC).
Files and Encoding
Working with a File
| Step | What happens | In Java |
|---|---|---|
| Create | A new, empty file appears on disk. | file.createNewFile(); opening 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 | Buffered data is flushed to disk and the OS resource is released. | close() or try-with-resources |
An unclosed file causes both data loss (buffered bytes never reach the disk) and a resource leak: the OS limits how many files can be open at once.
Files and Encoding
A First File Program
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 bytes
Merhaba, dünya!
FileWriterwrites text.FileOutputStreamwrites raw bytes;write(127)is the single byte7F.read()returns the byte as anintfrom 0 to 255.
Files and Encoding
Text Files
- Text files contain printable characters: letters, digits, punctuation, spaces, line breaks.
- Any text editor (Notepad, VS Code) can open and edit them. Examples: source code (
.java,.c),.txt,.csv,.html. - A character set / encoding is the table that says which number (which bytes) stores each character. Writer and reader must use the same encoding.
7 bits, 128 characters: English letters, digits, punctuation, control characters.
8 bits, 256 characters: Western Europe (Latin-1). Has é, ü, ö, ç; no ş, ğ, ı.
8 bits, Latin-5: the Turkish variant. Six Latin-1 letters are replaced by ğ, Ğ, ı, İ, ş, Ş.
The universal Unicode encoding: every language, 1–4 bytes. The default on the web and in Java 18+.
Files and Encoding
Binary Files
- Bytes are stored not as characters but in a format the program defines: numbers, pixels, audio samples, machine code.
- Meaningful to a computer (the right program); people cannot read them directly.
- Examples: executables (
.exe, Java's.classfiles), images (.png,.jpg), music (.mp3), video (.mp4), data files (.dat). - Advantage: smaller and faster to process; no number-to-text conversion.
FirstFile.class in a hex editor (first 32 bytes):
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/l
The same file opened in Notepad:
Êþº¾···A·\················java/lang/Object···<init>···()V······java/io/FileWriter······file.txt··············(
Every .class file starts with the bytes CA FE BA BE: the JVM recognizes the file type by this “magic number”.
Files and Encoding
Extended ASCII and Turkish Characters
- Extended ASCII uses 8 bits (1 byte) to represent 28 = 256 characters.
- 0–127: standard ASCII, the same in every table. 128–255: special characters, symbols and national letters.
- There is no single “extended ASCII”: the upper half depends on the code page. Turkish uses ISO-8859-9 (Latin-5) and Windows-1254.
| Byte | D0 | DD | DE | F0 | FD | FE | FC | E7 |
|---|---|---|---|---|---|---|---|---|
| ISO-8859-1 (Western Europe) | Ð | Ý | Þ | ð | ý | þ | ü | ç |
| ISO-8859-9 (Turkish) | Ğ | İ | Ş | ğ | ı | ş | ü | ç |
FE) is ş in one table and þ in the other. Opening a file with the wrong code page gives garbled text such as “þimdi”. The fix: Unicode / UTF-8, which covers every language.Files and Encoding
Writing a Number (127) to a File
- How a number is stored depends on its data type, its purpose and the file format.
- As text: the number is first turned into characters, one ASCII byte per digit: the code of
'1'is 49, not 1. - As binary: the binary value (0111 1111) is written directly, using as many bytes as the type needs. More efficient for numeric data.
Files and Encoding
Text or Binary? A Comparison
| How 127 is written | Size |
|---|---|
| ASCII / UTF-8 text file | 3 bytes |
| UTF-16 text file (no BOM) | 6 bytes |
Binary, byte | 1 byte |
Binary, short | 2 bytes |
Binary, int | 4 bytes |
- Text: human-readable, opens in any editor, portable across platforms. Logs, settings, CSV tables.
- Binary: stores numbers smaller and faster, but you must know the writer's format. Images, audio, database files.
- An
intis always 4 bytes, whether 7 or 2 000 000 000. In text the size depends on the digit count (7 → 1 byte, 2 000 000 000 → 10 bytes).
Java tools: DataOutputStream writes primitives in binary (writeByte, writeShort, writeInt…), DataInputStream reads them back in the same order; OutputStreamWriter turns characters into bytes with a given encoding.
Files and Encoding
Checking in Code: 127
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: 4
File System
The java.io.File Class
- A
Fileobject represents a path on disk: a file or a directory. It does not read or write the file's contents; streams do that. - It queries the file system and answers:
- Does the path exist? Is it a file or a directory?
- Is it readable, writable, executable? What is its size and last-modified time?
- It can create a file or directory, delete one, and list a directory's contents.
new File("sample.txt")creates nothing on disk; it only holds the path.
| Method | Returns |
|---|---|
exists() | whether the path exists (boolean) |
isFile() / isDirectory() | file / directory? |
canRead(), canWrite(), canExecute() | permissions |
createNewFile() | created? (false if it exists) |
mkdir() / mkdirs() | directory (with parents) |
delete() | deleted? (not a non-empty dir) |
list() / listFiles() | String[] / File[] |
length() | size (bytes, long) |
lastModified() | milliseconds since 1970 |
getName(), getAbsolutePath() | name, full path |
File System
Files and Directories with File
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: false
/works as a path separator on every system;File.separatoris also available.- A relative path is resolved against the program's working directory.
Reading and Writing Text
Reading a File with 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(); } } }
Java Input Output Streams
- A missing file throws a checked exception:
catchis required. hasNextLine(): is there a line?nextLine(): take it.- If opening fails,
scannerstaysnull: hence thefinallycheck.
Scanner reads files and other inputs such as the keyboard or a String. Imports: java.io.File, java.io.FileNotFoundException, java.util.Scanner. Scanner is AutoCloseable: with try-with-resources, no finally or null check is needed.
Reading and Writing Text · Step-by-step trace
try-with-resources: Closing Order
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"); } } }
The first resource in the parentheses is created; its constructor prints a message. a is now open.
The second resource, b, is opened. Resources are created left to right.
The block body runs; both resources are open.
An exception is thrown. Before control reaches catch, the resources are closed automatically.
Closing runs in reverse order: first close() on b, the last one opened.
Then a.close() runs. The exception is still in flight, not yet caught.
Only after the resources are closed does catch catch the exception. By now a and b are out of scope.
finally runs last. Order: open A, open B, body, close B, close A, catch, finally.
Reading and Writing Text
The Java I/O Library
- The
java.iopackage is a powerful, flexible toolkit for input and output, used for everything from files to network programming.
Receive and send data from sources such as files, the network and memory.
Supports both byte-based (binary) and character-based (text) I/O.
Data in a file can be read in order or by jumping to any position.
| Kind | Examples | Purpose |
|---|---|---|
| Classes | File | file and directory (path) operations |
InputStream, OutputStream | basic byte I/O | |
Reader, Writer | text (character) I/O | |
| Interfaces | Closeable, AutoCloseable | release the resource: close() |
Flushable | empty the buffer: flush() | |
| Exceptions | IOException | superclass of I/O errors |
FileNotFoundException, EOFException | no such file / unexpected end of file |
Reading and Writing Text
Byte-Oriented and Character-Oriented I/O
Byte streams
InputStreamandOutputStreamclasses- Data is handled as bytes (8 bits)
- Works with binary data: images, audio, video,
.class read()returns a byte from 0 to 255
Character streams
ReaderandWriterclasses- Data is handled as char (16-bit Unicode)
- More efficient for text data
- Decodes the encoding (UTF-8…): supports any language or alphabet
| Byte stream | Character stream | |
|---|---|---|
| Unit read | byte | char |
| File classes | FileInputStream, FileOutputStream | FileReader, FileWriter |
| Buffered | BufferedInputStream, BufferedOutputStream | BufferedReader, BufferedWriter |
| Use | any file, copying | text files only |
Bridge classes: InputStreamReader turns a byte stream into a character stream, OutputStreamWriter turns characters into a byte stream (this is where the encoding is applied).
Reading and Writing Text
Byte Stream Classes
Italic boxes are abstract classes; hollow-triangle arrows show inheritance. System.out is a PrintStream. Filter… subclasses wrap another stream to add a capability (buffering, reading primitives).
Reading and Writing Text
Character Stream Classes
FileReader is really an InputStreamReader: it decodes the bytes from a FileInputStream into characters with the chosen encoding. Likewise, FileWriter extends OutputStreamWriter.
Reading and Writing Text
Wrapper (Decorator) Streams
BufferedReader reader = new BufferedReader(new FileReader("sample.txt")); PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("file2.txt")));
- Each stream class does one job well; you combine capabilities by wrapping streams inside one another (the Decorator pattern).
- Think of a hose with a filter and then a spray nozzle on the end: the water (data) passes through each in turn.
- Closing the outermost stream (
close()) closes all the inner ones.
Reading and Writing Text
BufferedReader Line by Line: Step by Step
File only holds the path; the file is not open yet.
FileReader opens the file and BufferedReader wraps it. The read position is at the start.
readLine() reads a line and drops the ⏎. Not null → enter the loop.
The line is printed.
The next line is read: line = "Input Output".
The line is printed.
The next line is read: line = "Streams".
The line is printed.
End of file: readLine() returns null → the loop ends.
The try ends: reader is closed automatically; catch does not run.
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(); } } }
Reading and Writing Text
java.io.PrintWriter
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(); } } }
- Writes text files easily:
print,println,printf. - Writes other types by converting them to text.
- Creates the file if missing; otherwise truncates it.
- Don't forget
close: data may be left in the buffer.
Hello, world! This is a sample file. Pi is about 3.14 42
Reading and Writing Text
java.io.FileWriter
- Writes character-based data to files; it is a character stream (
Writer). - It has only
write(String),write(char[]),write(int c): formatting is limited, and line breaks (\n) must be written explicitly. - A lower-level, flexible approach; usually wrapped in a
BufferedWriterorPrintWriter. new FileWriter(name, true)appends to the end of the file;falseor no flag truncates it.
FileWriter | BufferedWriter | PrintWriter | |
|---|---|---|---|
| Write methods | write | write, newLine() | print, println, printf |
| Writing a number | convert to String first | convert to String first | directly: println(42) |
| Buffer | small internal buffer | 8192-char buffer | depends on the wrapped stream |
| Error reporting | IOException | IOException | checkError() |
Reading and Writing Text
FileWriter Example: Write and Append
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.
Hello, world! This is a FileWriter example. Appended line.
Reading and Writing Text
Specifying the Character Encoding
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, Ãnye
- Without an explicit encoding the default is used: UTF-8 in Java 18+, previously the OS setting (Windows-1254). Portable code names the encoding explicitly; in Java 10 and earlier, via the
InputStreamReaderbridge. - A character with no mapping becomes
?(3F):şis3Fin ASCII,C5 9Fin UTF-8.
Buffering
Buffering
- The basic methods:
read()reads a byte or a byte array,write()writes a byte or a byte array. - A separate disk access per byte slows the program badly: the disk is thousands of times slower than memory.
- The fix: collect data in a buffer in memory and read from or write to the disk in bulk. Fewer physical disk accesses.
Unbuffered: every write() call goes straight to the disk.
Buffered: write() calls first put the bytes in a buffer in memory.
When the buffer fills up, or on flush() or close(), the whole buffer is written to disk at once.
Buffering
Buffered Stream Classes
| Class | Wraps | What it does |
|---|---|---|
BufferedInputStream | InputStream | speeds up reading: on read() it pulls 8192 bytes from disk into a memory buffer at once |
BufferedReader | Reader | the same, for characters; plus readLine() |
BufferedOutputStream | OutputStream | speeds up writing: collects write() data in the buffer |
BufferedWriter | Writer | the same, for characters; plus newLine() |
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: 8
flush() empties the buffer to disk immediately; close() flushes first. With an unclosed buffered writer, the last data is lost.
Buffering · Step-by-step trace
Buffer and flush: Step by Step
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());
FileWriter creates the (empty) file. Writes go to the buffer in memory first.
Nothing written yet: 0 bytes.
print puts 7 characters in the buffer; the disk is untouched.
The file is still 0 bytes: the data waits in memory.
The second entry joins the buffer; the file is still 0 bytes.
flush() empties the buffer to disk: 14 bytes written.
The length is now 14.
The third entry goes into the buffer.
close() flushes first, then closes the file.
The file is 21 bytes. Without close, the last entry could have been lost.
PrintWriter never throws; writing to a closed stream fails silently. Only checkError() reveals the error.
Buffering
BufferedInputStream and BufferedReader
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()); }
Java I/O Buffer
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()); }
Java I/O Buffer
Buffering
How Much Does Buffering Help?
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(); } }
Unbuffered: 3151 ms Buffered : 94 ms
- The same 2 MB file, read byte by byte twice.
- Unbuffered: 2 097 152
read()calls = that many system calls. - Buffered: one system call per 8 KB, 256 in all. Tens of times faster.
- Times vary by machine; the ratio stays similar.
Other Byte Streams
java.io.FileInputStream
- Extends
InputStream; reads raw bytes straight from a file. Low-level: for non-text data such as images and audio. read(): one byte (0–255), −1 at end of file.read(byte[] b): reads up tob.lengthbytes and returns how many it read.- Awkward for text (multi-byte characters such as ü can be split); character classes such as
FileReaderare a better fit.
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)); } } } }
4: Hell 4: o, J 4: ava!
file.txt: “Hello, Java!”, 12 bytes, read in chunks of 4. new String(buf, 0, n) converts only the part that was read.
Other Byte Streams
java.io.ByteArrayInputStream
- Extends
InputStream; reads from a byte array in memory. No physical device is involved, so it is fast. - Read-only; its counterpart for writing to memory is
ByteArrayOutputStream. With large data, memory use can become a problem.
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!
Other Byte Streams
StringBufferInputStream: Deprecated
java.io.StringBufferInputStreamhas been deprecated since Java 1.1; avoid it.- It does not convert characters to bytes correctly (only the low 8 bits). Use
ByteArrayInputStream+getBytes(UTF_8)or aStringReaderinstead.
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
ş (351) → 95 = _, € → 172. Correct UTF-8: 197 159 226 130 172.
Other Byte Streams
PipedInputStream and PipedOutputStream
- Derived from
InputStream/OutputStream; they let two threads pass data safely. - One thread writes with a
PipedOutputStream, the other reads it with aPipedInputStream. The ends are connected withnew PipedOutputStream(pis). - Reads and writes are synchronized: the reader waits when the pipe is empty, the writer when it is full.
- Data flows one way only; two-way traffic needs two pipes.
- Using both ends in the same thread can cause a deadlock.
Other Byte Streams
Pipe Example
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.- When the writer calls
pos.close(), the reader'sread()returns −1 and the loop ends.
Other Byte Streams
java.io.SequenceInputStream
- Joins several
InputStreams into one sequential input stream: when the first ends (−1), it moves on to the second. - Merges data from different sources into one stream. If a stream fails, an
IOExceptionis thrown and the next one is not read.
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.
sis.close() closes the inner streams too.
Copying Files
Copying a File Byte by Byte
- Writes every byte read from the source file to the target: copies any kind of file (text, image,
.exe) intact. BufferedInputStreamandBufferedOutputStreamspeed up I/O by reading and writing through a buffer in bulk.bis.read()reads one byte and returns −1 at end of file.bos.write(b)writes that byte to the output file.- Keep the value in an
int, so that −1 can be told apart from the byte value 255.
The copy loop is a single line: while ((b = bis.read()) != -1) bos.write(b);
Copying Files
Byte-by-Byte Copy: Step by Step
The two File objects only hold paths.
FileOutputStream creates the target (truncating it if it exists): 0 bytes.
Both streams are wrapped in buffered streams; the buffers (8192 bytes) are empty.
First read(): the buffer is empty, so all 4 bytes come from disk in one go; the first byte, 74 ('J'), is returned.
write puts the byte in the output buffer; file2.txt is still 0 bytes.
No disk access this time: the byte comes from the buffer (97 = 'a').
The output buffer now holds 2 bytes.
No disk access this time: the byte comes from the buffer (118 = 'v').
The output buffer now holds 3 bytes.
No disk access this time: the byte comes from the buffer (97 = 'a').
The output buffer now holds 4 bytes.
The buffer is drained; a second disk read reports end of file: read() returns −1 and the loop ends.
close() flushes first: 4 bytes go to disk in one write, then fos closes.
The input streams are closed too.
2 disk reads (the second only reports end of file) and 1 write; unbuffered, it would take 5 reads and 4 writes.
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"); } }
Copying Files
Copying Block by Block
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"); } }
40000 bytes copied
- Reading in bulk improves performance.
read(buf)returns the number of bytes read.write(buf, 0, size)writes only the firstsizebytes.
new byte[1024 * 16]: data is processed in 16 KB chunks, so memory use stays constant however large the file is.
Copying Files
Copying Block by Block, Step by Step
A 16-byte array (8–16 KB in real programs).
Both resources are opened together; both close when the try ends.
read(buf) fills the array and returns 16.
write(buf, 0, 16): only the 16 bytes read are written.
The count is printed.
The next 16 bytes overwrite the same array.
write(buf, 0, 16): only the 16 bytes read are written.
The count is printed.
Only 7 bytes are left: the first 7 elements are refreshed, the other 9 are left over from the previous block!
write(buf, 0, 7): only the 7 bytes read are written. With write(buf), the 9 stale bytes would go too, and the copy would be 48 bytes.
The count is printed.
End of file: −1 is returned, > -1 is false, the loop ends.
The resources are closed; the copy matches the source: 16 + 16 + 7 = 39 bytes.
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"); } }
Copying Files
Copying a File Line by Line
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.txt
- Uses character streams: text files only.
readLine()drops the line terminator;printlnadds the system's own (Windows:\r\n, Linux:\n). The copy may not be byte-identical.pw.close()closes the whole chain (bw,fw).
Copying Files
Downloading a Web Page
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 bytes
- The source is the network, not a file:
url.openStream()returns anInputStream, and the copy loop is the same. new URL(String)is deprecated since Java 20; useURI.create(…).toURL().- The
forloop: read; if not −1, write; read again.
Copying Files
Shortcuts: transferTo and Files.copy
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 copied
Library methods copy in blocks internally. If the target exists, Files.copy throws FileAlreadyExistsException unless you pass REPLACE_EXISTING.
Copying Files
Ways to Copy
| Method | Unit | Best for |
|---|---|---|
Byte by byte (read()/write(int)) | 1 byte | learning; very slow unbuffered |
Block by block (read(byte[])) | 8–16 KB | any 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(src, dst) (Java 7+) | block | shortest file-to-file route |
IOException.Random Access
File Access: Sequential and Random
Sequential access
- Each read or write continues from the next position; going back needs special support (e.g.
mark/reset, within a limited buffer); you cannot jump around freely. - Used when the file's structure is unknown, or when making a copy.
- All streams (
FileInputStream,BufferedReader…) are sequential.
Random access
- Move to any position in the file and read or write there.
- Works when the size and position of records are known: record k = k × record size.
- Handy for reading one record or updating it in place.
Random Access
java.io.RandomAccessFile
| Member | Purpose |
|---|---|
RandomAccessFile(String name, String mode) | mode "r": read, "rw": read and write |
seek(long pos) | moves the file pointer to the given position |
getFilePointer() | pointer's offset from the start (bytes) |
length() | file length (bytes) |
read() / write(int b) | reads (returned as int) / writes one byte |
readInt(), writeInt(int), readDouble()… | read/write primitives in binary (int: 4 bytes) |
close() | releases system resources |
Unlike streams, one object both reads and writes; it is not part of the InputStream / OutputStream hierarchy.
Random Access
Sequential and Random Access: Code
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: 256
seek(100) moves the pointer to position 100, the 101st byte (positions start at 0). The 4 bytes there are 00 00 01 00, so readInt() returns 256. Here data is a 124-byte data file.
Random Access
Random Access to Records, Step by Step
"rw": the file is created if missing. The pointer is at 0.
Five grades to write.
Each writeInt writes 4 bytes and advances the pointer by 4.
Loop done: 5 × 4 = 20 bytes; the pointer is at the end (20).
length() = 20.
The 3rd record (index 2) starts at byte 8: we jump straight there without reading the others.
readInt() reads bytes 8–11: 90. The pointer moves to 12.
getFilePointer() = 12.
The 4th record also starts at 12; the pointer is already there.
50 replaces 45 in place; the rest of the file is untouched. A sequential stream can't do this.
Back to the start.
Read until the pointer reaches the length: 70 + 85 + 90 + 50 + 60 = 355.
The result is printed; then the file is closed.
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(); } }
Serialization
Serialization
- Serialization turns an object's state (its field values) into a byte sequence, so the object can be written to a file or sent over the network. The reverse is deserialization.
- For its objects to be serializable, a class must implement
java.io.Serializable(a marker interface with no methods). - Declaring a version ID,
serialVersionUID, is recommended; otherwise one is computed from the class structure, and old files become unreadable once the class changes. staticfields (they belong to the class) and fields markedtransientare not serialized; use this to leave out fields such as passwords.
Serialization
The Serialization Flow
A Student object lives in memory.
ObjectOutputStream.writeObject turns the object into bytes; the file starts with the magic number AC ED.
ObjectInputStream.readObject builds a new object from the bytes: same values, different object.
Serialization
A 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 + "]"; } }
implements Serializable: a marker interface with no methods.serialVersionUID: the class's version number. If writer and reader versions differ:InvalidClassException.- Fields must be serializable too; otherwise
NotSerializableException. readObjectreturnsObject: a(Student)cast is needed.
Serialization
Writing and Reading Back an Object
// 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]
Serialization
transient and static Fields
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 + "]"; } }
transient: the field is skipped during serialization; when read back it gets its default value (null, 0,false).- For fields that shouldn't or can't be stored: passwords, temporary caches, open files or connections.
staticfields belong to the class, not the object: they are never written to the file.
Serialization
transient and static: Experiment
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? false
password→null: not written.count→ 99: the last value in memory.==is false: the copy is a new object.
Serialization · Step-by-step trace
Serialization: Writing and Reading Back, Step by Step
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));
A new Account object on the heap: name and password are set. The static count lives in the class area: 0.
count belongs to the class, not the object; there is only one copy.
The stream opens and immediately writes a 4-byte stream header.
writeObject writes the class description and the fields: 63 bytes. transient password and static count are not written.
The stream is closed; the file stays at 63 bytes.
The class's count becomes 99. The file has no count, so reading can't change it.
The input stream opens and first checks the stream header.
A new object is built on the heap; the constructor is not called. name comes from the file; password gets the default, null.
toString() prints the fields of the object read back.
count is the last value in memory: 99.
Two separate objects: similar contents, different references.
NIO
NIO (New I/O)
- Java NIO (
java.nio, Java 1.4+) is a powerful API for advanced I/O: buffers, channels, selectors and file system integration. - It offers more performance and flexibility than classic
java.iostreams.
Memory areas that hold data temporarily.
Bidirectional connections that carry out I/O.
Manages many channels from one thread, watching for channels with pending input.
Represents file and directory paths (Java 7+, NIO.2).
NIO.2 (java.nio.file, Java 7+) added the Path and Files classes for file operations.
NIO
Stream or Channel?
Classic I/O (java.io) | NIO (java.nio) | |
|---|---|---|
| Core idea | stream | channel + buffer |
| Direction | one way: input or output | a channel can be two-way |
| Unit | byte / character | a buffer-sized block |
| Waiting | always blocking | non-blocking mode available |
| Many connections | one thread per connection | one thread + selector |
| When? | simple file/console work | servers with many connections, large files |
NIO
NIO Buffers
- A buffer is a fixed-size memory area that holds data temporarily (an array plus position bookkeeping).
- One class per primitive type:
ByteBuffer,CharBuffer,ShortBuffer,IntBuffer,LongBuffer,FloatBuffer,DoubleBuffer. - Create one with
ByteBuffer.allocate(1024), or wrap an existing array:ByteBuffer.wrap(arr).
| Property | Meaning |
|---|---|
| capacity | maximum number of elements; never changes |
| position | index of the next read or write |
| limit | first index that may not be read or written |
| mark | a position saved by mark(); reset() returns to it |
Always: 0 ≤ mark ≤ position ≤ limit ≤ capacity.
NIO
ByteBuffer Example
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 NIO
putwrites; the position moves to 14.flip(): limit = 14, position = 0: read mode.hasRemaining(): is position < limit?
NIO
Buffers and Non-ASCII 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
(char) buffer.get() is only correct for ASCII text. “Dünya” (Turkish for “world”) is 6 bytes in UTF-8 (ü = C3 BC); casting bytes one by one to char mangles the ü. Decode text with Charset.decode.
NIO
put, flip, get, compact, rewind, clear: Step by Step
Empty buffer: position 0, limit = capacity = 8.
put writes at the position and advances it by 1.
Position 2.
Position 3.
4 bytes written; position 4.
flip(): limit = old position (4), position = 0. Only the 4 bytes written can be read.
get() returns the byte at the position; the position becomes 1.
c2 = 'A'; 2 unread bytes remain (V, A).
compact(): the unread V, A are copied to the front; position 2, limit 8. The old bytes at 2–3 stay until overwritten.
'!' is written at position 2, over the old 'V'.
Switch to reading: limit 3 (V, A, !).
One byte is read ('V'); position 1.
rewind(): position 0, limit unchanged: the same data can be read again.
clear(): position 0, limit 8. The data is not erased; it just counts as “empty” and gets overwritten.
toString() shows the buffer's position, limit and capacity.
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); } }
NIO
Buffer Operations
| Method | What it does | position | limit |
|---|---|---|---|
put(x) | writes data at the position | +1 | — |
get() | reads the data at the position | +1 | — |
flip() | switches from writing to reading | 0 | old position |
rewind() | to reread the same data from the start | 0 | unchanged |
clear() | prepares for writing again; does not erase | 0 | capacity |
compact() | moves unread data to the front, keeps writing | remaining count | capacity |
mark() / reset() | marks the position / returns to the mark | — / mark | — |
Pros
- Flexible navigation and modification of data
- Efficient memory use: one area is reused again and again
Cons
- Tricky to use (forgetting
flipis a common bug) - Cannot be resized later
NIO
ByteBuffer Playground
Green cells lie between position and limit: free space in write mode, data to read in read mode. Try: put three times, flip, get twice, compact; or get without flip.
NIO
NIO Channels
- A channel handles input and output: it exchanges data with a file, a socket or some protocol.
- Data is always read (
read(buffer)) or written (write(buffer)) through a buffer.
| Channel type | Use |
|---|---|
FileChannel | reading and writing a file |
SocketChannel | data over a TCP socket |
ServerSocketChannel | accepting incoming TCP connections |
DatagramChannel | data over a UDP socket |
NIO
Opening and Closing Channels
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: true
FileChannel.open(path, options…) opens a file channel; SocketChannel.open() + connect opens a network channel. Channels must be closed too, with close() or try-with-resources.
NIO
Reading with FileChannel
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 demo
channel.read(buffer) reads into the buffer and returns the number of bytes read (−1 at end of file). Don't forget flip() before reading the buffer.
NIO
Writing with FileChannel
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 written
ByteBuffer.wrap(arr) uses an existing array as the buffer (position 0, limit = array length), so no flip() is needed. CREATE: create the file if missing.
NIO
Using SocketChannel
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 OK
The body of main. A network connection is a channel too: the same put / flip / write pattern. HTTP/1.1 requires the Host header.
NIO
NIO: Pros and Cons
Pros
- Performance: transfers in blocks, more efficiently than classic I/O
- Flexibility: buffers and channels; two-way channels
- One approach for both files and the network
- Many connections: a selector serves many channels from one thread; only active channels are processed
Cons
- Complexity: harder than classic I/O
- You must manage buffer state and failures (partial reads, dropped connections)
- Selectors have a learning curve: tracking many channels' state correctly
BufferedReader or Files is enough. Channels shine with very large files and many network connections.NIO
Path and Files (NIO.2)
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 lines
| Method | Purpose |
|---|---|
Path.of(…) / Paths.get(…) | builds a path (the modern File) |
Files.readAllLines, Files.readString | reads the whole file in one call (UTF-8) |
Files.write, Files.writeString | writes in one call |
Files.exists, size, copy, move, delete | file system operations |
NIO
NIO Selectors
- A mechanism for watching many channels from a single thread.
Selector.open()creates a new selector.- A channel is put in non-blocking mode and registered with the selector:
channel.register(selector, ops). SelectionKeyconstants say which events the channel waits for.select()blocks until at least one channel is ready.
| SelectionKey | Meaning |
|---|---|
OP_READ | the channel can be read |
OP_WRITE | the channel can be written |
OP_CONNECT | connection established |
OP_ACCEPT | a connection can be accepted |
NIO
A Server with a Selector
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 binds to port 8080, switches to non-blocking mode and registers for
OP_ACCEPT. select()returns the number of ready channels;selectedKeys()gives their keys.- Keys not removed with
clear()come back on the next round. - A real server registers each accepted client for
OP_READand reads its data.
Summary
Summary
| Topic | Key class / method | Remember |
|---|---|---|
| Streams | System.in, System.out, System.err, Scanner | data flows from source to destination in order |
| Text / binary | ASCII, ISO-8859-9, UTF-8; DataOutputStream | 127: 3 bytes as text, 4 as int; read and write with the same encoding |
| File system | File, Path, Files | File is just a path; it doesn't read contents |
| Reading/writing text | Scanner, BufferedReader, PrintWriter, FileWriter | readLine() gives null at the end; FileWriter(name, true) appends |
| Byte streams | FileInputStream, ByteArray…, Piped…, Sequence… | read() gives −1 at the end; keep it in an int |
| Buffering | Buffered…, flush() | batches disk access; close your streams |
| Copying | read(byte[]), write(b, 0, n), Files.copy | write only the n bytes read |
| Random access | RandomAccessFile, seek | record k = k × record size |
| Serialization | Serializable, ObjectOutputStream, transient | static/transient are not written |
| NIO | ByteBuffer, FileChannel, Selector | flip() after writing; clear()/compact() before writing again |
Summary
Common Mistakes (1)
error: unreported exception FileNotFoundException; must be caught or declared to be thrownnew FileReader("a.txt") must sit inside try-catch, or the method must declare throws IOException.
error: cannot find symbol symbol: class Scannerimport java.util.Scanner; (and import java.io.*; for I/O classes).
error: illegal escape character new File("C:\courses\notes.txt")\c and \n count as escape sequences. Write "C:\\courses\\notes.txt" or "C:/courses/notes.txt".
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Scanner.close()"If the file can't be opened, scanner stays null. You need if (scanner != null) or try-with-resources.
Summary
Common Mistakes (2)
Age: 19⏎ Name: Ayşe⏎ → output: [] 19nextInt() leaves the newline in the buffer, so the following nextLine() reads an empty line. Add a keyboard.nextLine(); in between.
bw.write("entry"); // no close note.txt size: 0The data stays in the buffer and the file looks empty. Call close() (or flush()); better yet, use try-with-resources.
b.put((byte) 'J'); b.put((byte) 'A'); b.get() → 0 (empty cell at position 2)You must flip() between writing and reading; otherwise you read what comes after the data, not the data.
java.io.NotSerializableException: CarThe class passed to writeObject (and its field types) must implements Serializable.
byte b; while ((b = (byte) in.read()) != -1)A byte of value 255 (it becomes −1) is mistaken for end of file. The right type is int.
out.write(buf); // stale data in last blockThe last block doesn't fill the array; the right call is write(buf, 0, size).
Summary
Practice Problems (1)
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());
- What does this code print?
12and345are written first as text, then in binary.
Show answer
- 6 and 8. Text:
"12 345"= 6 characters = 6 bytes. Binary: twoints = 2 × 4 = 8 bytes.
Summary
Practice Problems (2)
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()); }
- What does this code print?
a.txtdoes not exist at first.
Show answer
- cdef. The second
FileWritertruncates the file (“ab” is gone); the third, withtrue, appends.
Summary
Practice Problems (3)
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));
- What does this code print on its three lines?
Show answer
- 1 3 2 / 2 10 / 0 10 2.
flip: position 0, limit 3; oneget→ position 1, 2 remaining.compact: 2 and 3 move to the front; position 2, limit 10.clear: position 0, limit 10; nothing is erased, soget(0)= 2.
Summary
Practice Problems (4)
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()); }
- What does this code print?
Show answer
- 20 40 16. The records are 10, 20, 30, 40 (4 bytes each).
seek(4)→ 20.length() - 4= 12 → 40. After the read the pointer is at 16, the end of the file.
Summary
Exercises (1)
- Counter: write a program that counts the lines, words and characters (excluding line breaks) in
text.txt. The file: “Reading files in Java / is simple / (blank line) / and fun”.
Solution
int lines = 0, words = 0, chars = 0; try (BufferedReader br = new BufferedReader(new FileReader("text.txt"))) { String line; while ((line = br.readLine()) != null) { lines++; chars += line.length(); String t = line.trim(); if (!t.isEmpty()) words += t.split("\\s+").length; } } catch (IOException e) { System.err.println("Error: " + e.getMessage()); } System.out.println(lines + " lines, " + words + " words, " + chars + " characters");
4 lines, 8 words, 37 characters
Summary
Exercises (2)
- Squares: read
nfrom the keyboard; write the numbers 1..nand their squares tosquares.txt, then read the file back and compute the sum of squares.
Solution
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 sum = 0; try (Scanner in = new Scanner(new File("squares.txt"))) { while (in.hasNextInt()) { in.nextInt(); // i sum += in.nextInt(); // i * i } } System.out.println("Sum of squares: " + sum);
Sum of squares: 55
Summary
Exercises (3)
- Storing an array: serialize
int[] arr = {3, 1, 4, 1, 5}toarr.ser, read it back and print its length and sum (arrays are serializable).
Solution
int[] arr = {3, 1, 4, 1, 5}; try (ObjectOutputStream c = new ObjectOutputStream(new FileOutputStream("arr.ser"))) { c.writeObject(arr); } try (ObjectInputStream g = new ObjectInputStream(new FileInputStream("arr.ser"))) { int[] copy = (int[]) g.readObject(); int sum = 0; for (int x : copy) sum += x; System.out.println(copy.length + " elements, sum " + sum); }
5 elements, sum 14
Summary
Exercises (4)
- Grade file: write 5 grades as
ints withRandomAccessFile. Find the grade at a given rank without reading the whole file. Which position should youseekto? - Think: to read only the last record of a 10,000-line log file, is a sequential stream or random access better? What changes if lines have different lengths?
Answers / hints
f.seek((k - 1) * 4); int grade = f.readInt();The 3rd grade is at position 8.- With fixed-size records, random access: just
seek((n - 1) * size). With varying line lengths the position can't be computed: read sequentially from the start, or scan backwards from the end for\n.
Summary
References
- 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
java.io,java.nio,java.nio.channels,java.nio.filepackages. - 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.