Java File Basics
What a File Is
A file is a named sequence of bytes stored by the operating system on a disk or another storage device. A program can create a file, write bytes into it, read them back later — even after the program has stopped and restarted — and delete it. That durability is the reason files exist: memory (variables, objects, collections) is lost when the JVM exits, while files survive.
Applications use files constantly:
- configuration (
application.properties,config.yaml) - logs (
app.log) - data import and export (
customers.csv,report.pdf) - uploaded content (images, documents)
- caches and temporary working data
Every file has two pieces of information that matter to a program:
| Concept | Meaning | Example |
|---|---|---|
| Path | Where the file is — the folders leading to it plus its name | /home/asha/app/reports/sales.csv |
| Content | The bytes stored in it | month,total\nNov,5630.75\n |
The operating system also stores metadata: size, creation and modification times, permissions, whether it's hidden, and whether the entry is a regular file, a directory (folder) or a link.
A First Example
import java.io.IOException;
import java.nio.file.*;
public class First {
public static void main(String[] args) throws IOException {
Path file = Path.of("notes.txt");
Files.writeString(file, "Java file handling\nLine two\n");
String content = Files.readString(file);
System.out.print(content);
System.out.println("exists: " + Files.exists(file));
System.out.println("size: " + Files.size(file) + " bytes");
System.out.println("absolute: " + file.toAbsolutePath());
}
}
Output (the last line depends on the folder you run it from):
Java file handling
Line two
exists: true
size: 28 bytes
absolute: /home/asha/projects/demo/notes.txt
What each part does:
Path.of("notes.txt")creates aPathobject — a description of a location. Creating aPathdoesn't touch the disk; the file doesn't need to exist yet.Files.writeString(file, text)creates the file if it doesn't exist (or replaces its content if it does) and writes the text as UTF-8 bytes.Files.readString(file)reads the whole file back into aString.Files.existsandFiles.sizeask the operating system about the file's metadata. The size is 28 bytes: 18 characters in the first line, 8 in the second, plus two newline characters, all of which are one byte each in UTF-8.throws IOExceptionis required because every one of these operations can fail for reasons outside the program — a full disk, missing permissions, a deleted folder. File operations are the main source of checkedIOExceptions in Java.
The following lessons cover each step — creating, reading, writing, deleting, paths — in depth. This lesson explains the concepts underneath all of them.
Relative and Absolute Paths
"notes.txt" is a relative path: it has no starting folder, so Java resolves it against the current working directory — the folder the java command was started from. toAbsolutePath() shows the resulting full path.
An absolute path starts from the root of the file system:
| Operating system | Absolute path example |
|---|---|
| Linux / macOS | /home/asha/app/notes.txt |
| Windows | C:\Users\Asha\app\notes.txt |
The working directory is available as a system property:
System.out.println(System.getProperty("user.dir"));
This is a frequent source of confusion. When you run a program from an IDE, the working directory is usually the project root; when you run the same JAR from a terminal or a service manager, it's wherever that process was started. A relative path such as "data/input.csv" may therefore work in one place and fail with NoSuchFileException in another. Real applications usually read important locations from configuration (an absolute path or an environment variable) rather than relying on the working directory. The File Paths lesson covers paths in detail.
Inspecting Files and Directories
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
public class Info {
public static void main(String[] args) throws IOException {
System.out.println("working dir: " + System.getProperty("user.dir"));
Path dir = Files.createDirectories(Path.of("reports"));
Path report = Files.writeString(dir.resolve("sales.csv"), "month,total\nNov,5630.75\n");
for (Path p : new Path[] {dir, report, Path.of("missing.txt")}) {
System.out.printf("%-18s exists=%-5s dir=%-5s file=%-5s%n",
p, Files.exists(p), Files.isDirectory(p), Files.isRegularFile(p));
}
BasicFileAttributes attrs = Files.readAttributes(report, BasicFileAttributes.class);
System.out.println("size=" + attrs.size() + " readable=" + Files.isReadable(report)
+ " hidden=" + Files.isHidden(report));
try {
Files.size(Path.of("missing.txt"));
} catch (NoSuchFileException e) {
System.out.println("NoSuchFileException: " + e.getMessage());
}
}
}
Output (on Linux; the first line depends on where you run it):
working dir: /home/asha/projects/demo
reports exists=true dir=true file=false
reports/sales.csv exists=true dir=false file=true
missing.txt exists=false dir=false file=false
size=24 readable=true hidden=false
NoSuchFileException: missing.txt
Files.createDirectoriescreates thereportsfolder (and any missing parent folders) and does nothing if it already exists.dir.resolve("sales.csv")builds the pathreports/sales.csvby appending a name to a folder path. Windows would print it asreports\sales.csv.isDirectoryandisRegularFiledistinguish folders from files. A path that doesn't exist is neither.readAttributesreads several metadata values in a single call, which is more efficient than separate calls when you need many of them.- Asking for the size of a missing file throws
NoSuchFileException, a subclass ofIOExceptionwhose message is the path.
One important caution: Files.exists describes the file at the moment you ask. Another program could create or delete it a millisecond later. Code such as "if the file doesn't exist, create it" can therefore fail anyway. Robust code performs the operation and handles the exception instead of checking first — a theme in the next lessons.
Text Files and Binary Files
All files contain bytes. The difference between "text" and "binary" is only in how the bytes are interpreted:
| Text file | Binary file | |
|---|---|---|
| Content | Characters encoded as bytes using a character encoding | Bytes with a format-specific meaning |
| Examples | .txt, .csv, .json, .html, .java, .properties | .png, .jpg, .pdf, .zip, .class, .xlsx |
| Readable in a text editor | Yes | No (appears as garbage) |
| Java APIs | Reader/Writer, Files.readString, Files.readAllLines, BufferedReader | InputStream/OutputStream, Files.readAllBytes, Files.write(byte[]) |
Using a text API on a binary file corrupts it, because the bytes are converted to characters and back. Copying an image with readString/writeString produces a broken image; use the byte-based APIs (or Files.copy) for binary data.
Character Encoding
A character encoding (or charset) is the rule that converts characters to bytes and back. UTF-8 is the standard encoding for text today: ASCII characters take one byte, and other characters take two to four.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.HexFormat;
public class Bytes {
public static void main(String[] args) throws IOException {
Path file = Path.of("greeting.txt");
Files.writeString(file, "Hi ₹5", StandardCharsets.UTF_8);
byte[] raw = Files.readAllBytes(file);
System.out.println("characters: " + "Hi ₹5".length());
System.out.println("bytes: " + raw.length);
System.out.println("hex: " + HexFormat.ofDelimiter(" ").formatHex(raw));
System.out.println("as UTF-8: " + new String(raw, StandardCharsets.UTF_8));
System.out.println("as Latin-1: " + new String(raw, StandardCharsets.ISO_8859_1));
System.out.println("default charset: " + java.nio.charset.Charset.defaultCharset());
}
}
Output (Java 18 or later):
characters: 5
bytes: 7
hex: 48 69 20 e2 82 b9 35
as UTF-8: Hi ₹5
as Latin-1: Hi â¹5
default charset: UTF-8
How to read this:
- The text has 5 characters, but the file has 7 bytes.
H,i, space and5are one byte each (48 69 20 35); the rupee sign₹needs three bytes in UTF-8 (e2 82 b9). - Decoding the bytes with the same encoding (UTF-8) gives the original text back.
- Decoding them with a different encoding (ISO-8859-1, "Latin-1", which maps every single byte to one character) turns the three bytes of
₹into three wrong characters —â, an invisible control character, and¹. This garbled text is called mojibake, and it's what you see when a program reads a file with the wrong encoding. HexFormat(Java 17+) prints bytes as hexadecimal for inspection.
Since Java 18 (JEP 400), the default charset is UTF-8 on all platforms. On Java 17 and earlier it depended on the operating system — often windows-1252 on Windows — so the same program could write different bytes on different machines. The Files.readString, writeString, readAllLines and newBufferedReader/Writer methods have always used UTF-8 when no charset is given, but older classes such as FileReader and FileWriter used the platform default. Passing StandardCharsets.UTF_8 explicitly makes code behave identically on every Java version and operating system.
Line Separators
Text files mark the end of a line with special characters, and operating systems don't agree on which:
| System | Line separator | Escape in Java |
|---|---|---|
| Linux, macOS | LF | "\n" |
| Windows | CR LF | "\r\n" |
System.lineSeparator() returns the current platform's separator, and BufferedWriter.newLine() writes it. Java's line-reading methods (readAllLines, BufferedReader.readLine, Files.lines) accept \n, \r\n and \r, so files from any platform can be read. When producing files for another system or a specific format, choose the separator deliberately: CSV files defined by RFC 4180 use CRLF, while most Unix tools expect LF.
java.io and java.nio.file
Java has two generations of file APIs, and you'll meet both in real code:
java.io (Java 1.0) | java.nio.file (Java 7, "NIO.2") | |
|---|---|---|
| Represents a location | java.io.File | java.nio.file.Path |
| Operations | Methods on File, plus stream classes such as FileInputStream, FileReader | Static methods in java.nio.file.Files |
| Error reporting | Many methods return boolean (delete() returns false without saying why) | Methods throw specific exceptions (NoSuchFileException, AccessDeniedException, DirectoryNotEmptyException) |
| Encoding | Older reader/writer classes used the platform default (before Java 18) | UTF-8 by default |
| Extras | — | Symbolic links, file attributes and permissions, directory walking, file watching, pluggable file systems (e.g. ZIP files) |
The java.io stream classes (InputStream, OutputStream, Reader, Writer, BufferedReader and others) are still the foundation for reading and writing data and are used everywhere, including by Files. What java.nio.file replaced is mainly the File class for locating and managing files.
For new code, use Path and Files to work with files, and convert when an older API needs a File: path.toFile() and file.toPath(). Both styles are covered in this section — java.io in lessons such as File Class, FileInputStream and FileOutputStream, and java.nio.file in NIO Basics and Files API.
Closing Files
When a program opens a file for reading or writing through a stream, reader or writer, the operating system allocates a file handle to it. Handles are limited per process, and on Windows an open file often can't be deleted or renamed by other programs. A stream must therefore always be closed when you're done with it — best done with try-with-resources:
try (BufferedReader reader = Files.newBufferedReader(Path.of("sales.csv"))) {
System.out.println(reader.readLine());
} // the file is closed here, even if readLine() throws
The convenience methods Files.readString, Files.writeString, Files.readAllLines and Files.write open and close the file internally, so they need no try-with-resources. Methods that return a stream or reader you use afterwards — Files.newBufferedReader, Files.newBufferedWriter, Files.newInputStream, Files.lines, Files.list, Files.walk — leave the file open until you close it.
Typical Exceptions in File Handling
| Exception | Meaning |
|---|---|
NoSuchFileException | The file or a folder in its path doesn't exist |
FileAlreadyExistsException | Creating a file that already exists (with options that forbid replacing it) |
AccessDeniedException | The operating system refused access (permissions, read-only file, file locked) |
DirectoryNotEmptyException | Deleting a folder that still contains entries |
NotDirectoryException | Treating a regular file as a folder |
FileNotFoundException | The java.io equivalent of "can't open this file" (missing file, folder instead of file, or no permission) |
MalformedInputException | Reading text whose bytes aren't valid in the chosen encoding |
IOException | The common parent of all of the above, plus general failures such as a full disk |
All of them are subclasses of IOException, so a single catch (IOException e) handles any of them, while more specific catch blocks let you respond differently — for example, creating a default configuration on NoSuchFileException but reporting a permissions problem on AccessDeniedException.