1. Introduction
In programming you almost always need to work with files. The examples are familiar to everyone: saving note text, game progress, copying an image, or reading settings from a configuration file.
In Java there are modern and convenient tools for this: Path and Files from the java.nio.file package. They allow you to open a file, read its contents, write text, or even copy an image in just a few lines of code.
File path (Path)
A file always lives somewhere on disk, and to access it, you need to specify a path. For this Java provides the Path class, and you can create a new object using Path.of().
Path path = Path.of("hello.txt"); // relative path
Path absPath = Path.of("C:/Users/Me/image.png"); // absolute path (Windows)
Explanation:
- A relative path looks for the file in the project's current folder (for example, "hello.txt").
- An absolute path specifies the full address: drive, folders, and file name.
2. Working with text files
From Java’s point of view, all files fall into two types—text and binary. If the contents can be represented as human-readable text, it is a text file. In all other cases, it is just a set of bytes (a binary file).
Writing text to a file — writeString
To write a string to a file, use the writeString method.
Path p = Path.of("hello.txt");
Files.writeString(p, "Hello, file!");
What happened here:
- we create a Path object that points to "hello.txt";
- we write the string there with the writeString method;
- if the file did not exist, it will be created automatically.
This way you can easily save notes or messages to a text file.
Reading text from a file — readString
The readString method lets you load the entire file into a single string.
Path p = Path.of("hello.txt");
String content = Files.readString(p);
System.out.println(content);
Now the variable content holds the file contents. This is convenient for small files: configs, texts, JSON documents.
3. Working with binary files
Not all files are made of text. Images, music, archives—these are sequences of bytes. To work with them there are the write and readAllBytes methods.
Writing bytes to a file — write
The write() method allows you to write a byte array to a file. It is also called a buffer (byte buffer).
byte[] data = {65, 66, 67, 68}; // characters A B C D
Files.write(Path.of("letters.bin"), data);
Here we wrote a byte array to the file. If you open the file as text, it will contain the letters "ABCD".
Reading bytes — readAllBytes
To get the file contents back as a byte array, use the readAllBytes method.
byte[] buffer = Files.readAllBytes(Path.of("letters.bin"));
// print the read byte array to the screen
for (byte b : buffer)
{
System.out.print((char)b + " ");
}
You will see on the screen:
A B C D
This approach is used to work with any binary files—images, documents, music.
4. Common file handling scenarios
The most common scenario when working with files is probably copying a file.
Copying files
To copy a file, you can simply read it into a byte array and write it to another file.
Path in = Path.of("logo.png");
Path out = Path.of("logo_copy.png");
byte[] bytes = Files.readAllBytes(in);
Files.write(out, bytes);
This way you can copy images, documents, and any other files without caring about their format.
Checking existence and size
Sometimes you need to make sure that a file exists and find out its size. For this there are the exists and size methods.
Path p = Path.of("hello.txt");
if (Files.exists(p))
{
long size = Files.size(p);
System.out.println("File found, size: " + size + " bytes");
}
else
{
System.out.println("File not found!");
}
This is useful for diagnostics: you will know for sure whether you are working with the correct file.
5. Exceptions
Working with files can fail: the file is missing, you lack permissions, the disk is full, or the file is locked by another program. Therefore you should wrap disk operations in try-catch, or propagate exceptions outward using throws.
try
{
String content = Files.readString(Path.of("hello.txt"));
System.out.println(content);
}
catch (IOException e)
{
System.out.println("Read error: " + e.getMessage());
}
This way the program won’t crash, but will politely inform the user what happened. If needed, you can propagate the IOException further up the stack from a method using the throws keyword.
GO TO FULL VERSION