Lesson · File I/O
Legacy java.io: File, streams and the classic API
12 min readLegacy java.io
java.io is the 1995 layer: File for paths, concrete streams for files, BufferedReader for lines. It still appears in every codebase and job interview, and its two famous traps, default charsets and unchecked File metadata, still ship to production.
File is a path, not a file
A File object is a pathname with convenience methods; creating it does not touch the disk. exists(), isDirectory(), length() each consult the file system and can flip between calls: the file can vanish mid-method, which is why every such check is advisory and the real operation must still handle failure.
Paths are strings glued together, so the separator problem is the consumer's: File.separator exists because earlier Java wrote paths with "/" on systems that use backslashes. Modern replacement is Path.of with resolve, but File survives in method signatures, walk code and interview questions, so reading it fluently matters.
File file = new File("data", "notes.txt"); // no disk access yet file.exists(); // consult the file system file.mkdirs(); // creates parents too: plural s matters
The concrete streams and their pairs
Four classes do most of the work: FileInputStream and FileOutputStream for bytes, FileReader and FileWriter for characters. Each maps to a modern Files.new* counterpart, and each carries the same obligation: close them, prefer buffering around them, and never let the writer's internal buffer swallow your last bytes.
FileWriter and FileReader are the trap pair: they use the platform default charset, which varies per machine. The replacement is newBufferedWriter with an explicit StandardCharsets.UTF_8, and the same rule as the concepts lesson: characters need a named charset.
try (var writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) { writer.write("jvm"); } // FileWriter equivalent would use the machine's default charset: avoid
Reading lines without reinventing readLine
BufferedReader.readLine returns one line without its terminator, null at end of stream, and works with \\n, \\r\\n and \\r. The pattern while ((line = reader.readLine()) != null) is the classic loop every Java developer has written and every reviewer recognizes.
For in-memory text, Files.readAllLines is one call. For streaming line processing, Files.lines returns a lazy Stream<String> that must be closed (try-with-resources) since it holds an open file handle.
try (var reader = new BufferedReader(new FileReader(file))) { String line; while ((line = reader.readLine()) != null) { process(line); } }
Legacy I/O board · read it fluently, convert on sight
pick a classFiles.newBufferedWriter(path, StandardCharsets.UTF_8)
job
the character pair: text to and from a file
trap
FileWriter and FileReader use the machine default charset: a silent portability bug. The Files.new* pair takes the charset explicitly.
Scanner: friendly tokenizer, modest engine
Scanner splits input by delimiters and parses tokens: nextInt, nextDouble, next, hasNext, nextLine. It is the right tool for small, structured input (keyboard, test fixtures, config stanzas) and the wrong one for large files: tokenization goes through regex machinery, so throughput lags a buffered read by an order of magnitude.
The classic Scanner bug is the newline: nextInt leaves the line terminator in the buffer, and the following nextLine returns an empty string. Either consume it deliberately or stick to one method family per input.
Scanner scanner = new Scanner("42 ada\n7 linus"); scanner.nextInt(); // 42 scanner.next(); // ada; adds no newline trouble when not mixing nextLine scanner.nextInt(); // 7
When legacy java.io is still the right answer
The modern recommendation is java.nio.file for anything path-shaped and java.io streams wrapped over it. The legacy types keep real use cases:
- Method signatures and frameworks: any API older than 2011 expects File or InputStream; adapt at the edge.
- Stream decorators remain shared: BufferedInputStream, DataInputStream and ObjectInputStream are java.io classes used over NIO-backed streams every day.
- Char-level flexibility: Reader/Writer remain the base for text processing frameworks; NIO files often hand back an InputStream for you to wrap.
- In-memory and process streams: ByteArrayInputStream and PipedInputStream have no NIO equivalents and belong to java.io by design.
Fluency in the old layer pays
Every server codebase opens a File here, wraps a stream there. Knowing which legacy types to read fluently, which to convert on sight (FileReader and FileWriter), and which to leave alone (process and memory streams) is what the interview and the code review both check.
Interview angles
Does new File("x") create a file?+
No. File is an immutable pathname abstraction; creating the object touches nothing. Files are created by writers, createNewFile or Files.createFile, and existence checks are advisory snapshots.
Why is FileWriter dangerous?+
It uses the platform default charset, so the same code writes different bytes on different machines: a silent portability bug. Use Files.newBufferedWriter with StandardCharsets.UTF_8 instead.
readLine semantics?+
Returns the line without its terminator, recognizes \n, \r\n and \r, and returns null at end of stream: the loop condition is != null, never isEmpty(). It blocks until a line or EOF arrives.
Scanner versus BufferedReader for large files?+
BufferedReader (or Files.lines) reads by lines with minimal machinery and scales. Scanner tokenizes via regex and parses convenient types; for gigabytes of text it is the wrong tool, for a few hundred tokens it is the fastest to write.
What is the newline trap with Scanner?+
nextInt and friends consume only the token, leaving the line terminator in the buffer; the next nextLine returns an empty string. Consume the remainder deliberately (scanner.nextLine()) or stay within one family of methods.