Java File Basics

Su Suriya Ravichandran Updated 18 Nov 2026
9 min read ·Lesson 134 of 306

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:

ConceptMeaningExample
PathWhere the file is — the folders leading to it plus its name/home/asha/app/reports/sales.csv
ContentThe bytes stored in itmonth,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:

  1. Path.of("notes.txt") creates a Path object — a description of a location. Creating a Path doesn't touch the disk; the file doesn't need to exist yet.
  2. 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.
  3. Files.readString(file) reads the whole file back into a String.
  4. Files.exists and Files.size ask 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.
  5. throws IOException is 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 checked IOExceptions 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 systemAbsolute path example
Linux / macOS/home/asha/app/notes.txt
WindowsC:\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.createDirectories creates the reports folder (and any missing parent folders) and does nothing if it already exists.
  • dir.resolve("sales.csv") builds the path reports/sales.csv by appending a name to a folder path. Windows would print it as reports\sales.csv.
  • isDirectory and isRegularFile distinguish folders from files. A path that doesn't exist is neither.
  • readAttributes reads 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 of IOException whose 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 fileBinary file
ContentCharacters encoded as bytes using a character encodingBytes with a format-specific meaning
Examples.txt, .csv, .json, .html, .java, .properties.png, .jpg, .pdf, .zip, .class, .xlsx
Readable in a text editorYesNo (appears as garbage)
Java APIsReader/Writer, Files.readString, Files.readAllLines, BufferedReaderInputStream/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 and 5 are 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:

SystemLine separatorEscape in Java
Linux, macOSLF"\n"
WindowsCR 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 locationjava.io.Filejava.nio.file.Path
OperationsMethods on File, plus stream classes such as FileInputStream, FileReaderStatic methods in java.nio.file.Files
Error reportingMany methods return boolean (delete() returns false without saying why)Methods throw specific exceptions (NoSuchFileException, AccessDeniedException, DirectoryNotEmptyException)
EncodingOlder 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

ExceptionMeaning
NoSuchFileExceptionThe file or a folder in its path doesn't exist
FileAlreadyExistsExceptionCreating a file that already exists (with options that forbid replacing it)
AccessDeniedExceptionThe operating system refused access (permissions, read-only file, file locked)
DirectoryNotEmptyExceptionDeleting a folder that still contains entries
NotDirectoryExceptionTreating a regular file as a folder
FileNotFoundExceptionThe java.io equivalent of "can't open this file" (missing file, folder instead of file, or no permission)
MalformedInputExceptionReading text whose bytes aren't valid in the chosen encoding
IOExceptionThe 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java File Basics and get answers drawn from it.

Signed-in readers only.