I/O Operations in Java
Learn console input and output, formatted printing, and reading and writing files in Java with practical Docker-ready examples
Input and output (I/O) is how a program talks to the outside world — printing to the terminal, reading what a user types, and persisting data to files. You have already used System.out.println to print text; this tutorial goes deeper into formatted output, reading from standard input, and working with files.
As a class-based, object-oriented language, Java models I/O through objects: System.out is a PrintStream, Scanner wraps an input source, and the modern java.nio.file.Files class exposes static helpers for whole-file operations. Java also uses checked exceptions for I/O — the compiler forces you to acknowledge that reading or writing a file might fail. That verbosity is deliberate: it makes error handling part of the type system rather than an afterthought.
In this tutorial you will format console output with printf, read typed input with Scanner, write and read files with Files, and handle I/O errors with try/catch.
Formatted Console Output
println prints a value followed by a newline, and print prints without one. For anything more structured, printf (and its sibling String.format) use C-style format specifiers: %s for strings, %d for integers, %f for floating point, and %n for a platform-appropriate newline.
Create a file named FormattedOutput.java:
| |
You can run this example with:
| |
It prints:
Language: Java
Java first appeared in 1995.
Market share: 15.3%
[Java ]
Reading Console Input
To read what a user types, wrap System.in in a Scanner. Scanner parses input into the type you ask for: nextLine() reads a full line of text, while nextInt() reads the next integer token.
Create a file named ConsoleInput.java:
| |
Because this program reads from standard input, pipe answers into the container and add the -i (interactive) flag so Docker forwards stdin:
| |
With Ada and 1990 as input, it prints:
What is your name?
What year were you born?
Hi Ada, you are about 36 this year.
Reading and Writing Files
Modern Java handles files through java.nio.file.Files and Path. The Files class offers concise static methods for the common cases: write dumps a list of lines to a file, readAllLines reads them all back, and writeString (with StandardOpenOption.APPEND) adds to an existing file. Because these operations can fail — a disk fills up, a path is missing — they throw the checked IOException, so the method must either declare throws IOException or catch it.
Create a file named IoOperations.java:
| |
Running with Docker
The file I/O example above is the most complete, so use it to see everything working together. It compiles and runs entirely inside the container, writing build.log into your mounted directory:
| |
Expected Output
Running IoOperations produces:
Grace made 42 commits (87.6% coverage).
Wrote 3 lines to build.log
File contents:
line 1 -> compile: OK
line 2 -> test: OK
line 3 -> package: OK
After append, total lines: 4
Handled missing file: does-not-exist.txt
After it finishes, a build.log file will remain in your working directory containing the four written lines.
Key Concepts
- I/O is object-based —
System.outis aPrintStream,Scannerwraps an input source, andPathrepresents a filesystem location. You compose these objects rather than calling free functions. printfandString.formatformat output — use%s,%d, and%.1ffor values,%nfor a portable newline, and%%for a literal percent sign.Scannerreads typed input —nextLine()reads a whole line whilenextInt()reads a single number; alwaysclose()the scanner when you are done.java.nio.file.Filesis the modern file API —Files.write,Files.readAllLines, andFiles.writeStringcover most everyday reading and writing without manual streams.StandardOpenOption.APPENDadds to a file — without it, writing replaces the existing contents.- I/O uses checked exceptions — methods that touch the filesystem throw
IOException, so you must either declarethrows IOExceptionor wrap the call intry/catch. - Catch specific exceptions — handling
NoSuchFileExceptionseparately lets you react to a missing file distinctly from other I/O failures.
Running Today
All examples can be run using Docker:
docker pull eclipse-temurin:21-jdk
Comments
Loading comments...
Leave a Comment