Java File I/O

The code of the HappyCoders.eu article series on files in Java – one package per article. Every class with a main() method is one chapter of its article and prints the outputs shown there.
Articles
| Article |
Package |
| Java File I/O: Files, Streams, Readers, and Writers at a Glance – the overview of the series (English, German) |
eu.happycoders.overview |
| Java BufferedReader (English, German) |
eu.happycoders.bufferedreader |
| Java PrintWriter (English, German) |
eu.happycoders.printwriter |
| Java FileReader (English, German) |
eu.happycoders.filereader |
| Java FileWriter (English, German) |
eu.happycoders.filewriter |
| Serialization in Java (English, German) |
eu.happycoders.serialization |
| Creating, copying, moving, and deleting files and directories (English, German) |
eu.happycoders.files |
| Listing directory contents (English, German) |
eu.happycoders.listing |
| How to get the current working directory (English, German) |
eu.happycoders.workingdirectory |
Running the examples
The examples use Java 25 language features and need Java 25 or newer. Build once with mvn compile, then run a class from the repository root:
java -cp target/classes eu.happycoders.<package>.<ClassName>
Files the examples create go into target/; the serialization examples write their .ser files into the current directory.
Java File I/O overview – eu.happycoders.overview
The examples read the small log file files/server.log and write into target/.
Intro – writes a string to a file with Files.writeString() and reads it back with Files.readString()
Ch1Tasks – the one-liners of the task table: reading, writing, appending, checking, creating, copying, moving, deleting, and listing
Ch2TwoApis – File.delete() and File.listFiles() return false and null, Files.delete() and Files.list() throw an exception that names the reason
Ch3StreamModel – the word “Grüße” read as bytes with a FileInputStream and as characters with a FileReader, and read through a BufferedReader around an InputStreamReader around a FileInputStream
Ch4Reading – counts the lines per log level with Files.lines() and groupingBy()
Ch5Writing – writes the counts with a PrintWriter around Files.newBufferedWriter()
Ch6Exceptions – a missing file, a directory, and an ISO-8859-1 file read as UTF-8 with Files.lines()
Ch7Console – IO.readln() and IO.println() (Java 25)
Java BufferedReader – eu.happycoders.bufferedreader
Most examples read the small log file files/server.log.
Intro – reads the log file line by line
Ch1Creating – Files.newBufferedReader(), FileReader, InputStreamReader around a GZIPInputStream, an own buffer size, and a Latin-1 file read as UTF-8
Ch2ReadLine – line terminators, empty lines, and the end of the input
Ch3Lines – lines() with filter() and groupingBy(), an UncheckedIOException while streaming, and Files.lines()
Ch4ReadAll – readAllLines() and readAllAsString() (Java 25), also after a readLine()
Ch5Characters – read() and read(char[], int, int)
Ch6MarkReset – an optional header line with mark() and reset(), and skip()
Ch6Ready – ready() returns false, yet the next readLine() returns a line
Ch7Console – reading lines from System.in with the charset from stdin.encoding (Java 25)
Ch7Readln – IO.readln() (Java 25)
Ch8Scanner – tokens with Scanner and with split(), and how both classes report an IOException
Ch9Closing – closing the BufferedReader closes the reader inside it
Ch10Mistakes – calling readLine() twice per loop iteration
Java PrintWriter – eu.happycoders.printwriter
Most examples write the small log file target/server.log, the file the BufferedReader examples read.
Intro – writes the log file with printf()
Ch1Creating – new PrintWriter(String) with and without a charset, a PrintWriter around Files.newBufferedWriter(), and one around a GZIPOutputStream
Ch1WriteCalls – counts the write calls that arrive below a PrintWriter, with and without a BufferedWriter in between
Ch1Append – appending to a file: APPEND alone, CREATE and APPEND, and a FileWriter with append = true
Ch2Print – print() and println() for different types and null, the line separator, write(int) vs. print(int), and append()
Ch3Printf – format strings, the locale, chained printf() calls, and a missing argument
Ch4Flush – when the bytes reach the file, with and without autoFlush
Ch5CheckError – a failing writer, writing after close(), and the euro sign in ISO-8859-1
Ch6Closing – closing the PrintWriter closes the writer inside it, and what closing a PrintWriter around System.out does
Ch7StringWriter – text and a stack trace into a string, and the same with formatted() and StringBuilder
Ch8Console – a PrintWriter around System.out and System.console().writer()
Ch9PrintStream – how often a PrintStream and a PrintWriter, both with autoFlush, flush their stream
Ch10Mistakes – a PrintWriter that is never closed leaves the file empty
Java FileReader – eu.happycoders.filereader
Most examples read the small log file files/server.log.
Intro – reads the log file with readAllAsString() (Java 25)
Ch1Creating – a FileReader from a file name, a File, and a Path, getEncoding() for different charsets, and files that cannot be opened
Ch2Read – read() character by character, and an emoji arriving as two halves of a surrogate pair
Ch2ReadArray – read(char[]) in blocks, and what is left in the array after the last block
Ch2ReadAll – readAllLines() and readAllAsString() (Java 25), also after skip()
Ch2TransferTo – re-encoding a file from ISO-8859-1 to UTF-8 with transferTo()
Ch2Unsupported – mark() and reset() are not supported
Ch3Replacement – a Latin-1 file read as UTF-8: replacement characters from a FileReader, a MalformedInputException from an InputStreamReader with a reporting decoder
Ch3Bom – a UTF-8 byte order mark arrives as the first character
Ch4InputStreamReader – a classpath resource read with an InputStreamReader, and an unknown charset name
Ch5BufferedReader – a BufferedReader around a FileReader
Ch6Binary – a binary file read with a FileReader and with a FileInputStream
Ch8Closing – reading after close(), and open file descriptors of FileReaders that are never closed (Linux and macOS)
Java FileWriter – eu.happycoders.filewriter
Most examples write lines of the log file files/server.log into target/server.log.
Intro – writes two log lines
Ch1Creating – a FileWriter from a file name, a File, and a Path, overwriting and appending, appending to a file that does not exist, getEncoding(), and files that cannot be created
Ch2Write – write(int) with the two halves of a surrogate pair, with a number, and with a code point; write(String) and append(), also with null
Ch2Flush – when the bytes reach the file: flush(), many short writes through the 512-byte buffer, and one long write that grows it to 8,192 bytes
Ch3Unmappable – the euro sign in ISO-8859-1: a question mark from a FileWriter, an UnmappableCharacterException from an OutputStreamWriter with a reporting encoder, from Files.newBufferedWriter(), and from Files.writeString(); half a surrogate pair at the end of a string
Ch4OutputStreamWriter – an OutputStreamWriter around a GZIPOutputStream, and an unknown charset name
Ch5BufferedWriter – a BufferedWriter around a FileWriter
Ch6Binary – all 256 byte values written with a FileWriter and with a FileOutputStream
Ch8Closing – a FileWriter that is never closed leaves the file empty, also after a garbage collection; writing after close()
Serialization – eu.happycoders.serialization
The examples work on a small order model: the classes Order and Customer and the record OrderItem. Chapters that need a variant of a class – one that is not serializable, has no serialVersionUID, or validates in readObject() – keep it in a package of its own (graph, transients, versioning, inheritance, custom, special, filter).
Intro – writes an order into a file and reads it back
Ch1Writing – ObjectOutputStream: writing into a byte array, the first bytes of the stream, buffering
Ch2Reading – ObjectInputStream: pattern matching on the result, several objects in one stream, buffering, a file that is not a serialization stream
Ch3ObjectGraph – NotSerializableException, shared references, the same object written twice, reset() and writeUnshared()
Ch4Transient – transient fields after deserialization and how readObject() restores them
Ch5Versioning – the computed serialVersionUID and what happens when a class changes between writing and reading
Ch5Misdeclaration – a misdeclared serialVersionUID, for the JFR event jdk.SerializationMisdeclaration