Java File Class

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 140 of 306

What java.io.File Is

java.io.File is Java's original class for working with file and folder paths and performing basic file-system operations. It has existed since Java 1.0, so you'll find it throughout older code, many libraries, and APIs such as FileReader, FileInputStream, ProcessBuilder.directory() and Swing's JFileChooser.

Despite its name, a File object is not a file and doesn't hold any content. It's an abstract representation of a path — exactly like java.nio.file.Path. Creating new File("report.pdf") doesn't create anything on disk, and the file doesn't need to exist. Methods such as exists(), length() or delete() are what actually ask the operating system about, or change, the file at that location.

Since Java 7, Path and Files are the recommended API for new code, because File has several design problems (covered below). Still, you need to understand File to read and maintain existing code and to work with APIs that require it.

Creating File Objects

File a = new File("course-data/lessons.txt");        // a path string
File b = new File("course-data", "lessons.txt");     // parent string + child name
File c = new File(new File("course-data"), "lessons.txt"); // parent File + child name
File d = Path.of("course-data", "lessons.txt").toFile();    // from a Path

The two-argument constructors join the parent and child with the platform separator (/ or 0), which is safer than concatenating strings. All four objects represent the same relative path. As with Path, a relative path is resolved against the working directory (user.dir`) when the file system is accessed.

Inspecting a File

import java.io.*;

public class F1 {
    public static void main(String[] args) throws IOException {
        File dir = new File("course-data");
        File file = new File(dir, "lessons.txt");
        File sameFile = new File("course-data/../course-data/lessons.txt");

        System.out.println("mkdir: " + dir.mkdir() + ", again: " + dir.mkdir());
        try (FileWriter w = new FileWriter(file)) {
            w.write("1. Variables\n2. Loops\n");
        }

        System.out.println("getName:      " + file.getName());
        System.out.println("getPath:      " + file.getPath());
        System.out.println("getParent:    " + file.getParent());
        System.out.println("exists:       " + file.exists() + ", isFile: " + file.isFile() + ", isDirectory: " + file.isDirectory());
        System.out.println("length:       " + file.length() + " bytes");
        System.out.println("canRead:      " + file.canRead() + ", canWrite: " + file.canWrite());
        System.out.println("equals:       " + file.equals(sameFile));
        System.out.println("canonical eq: " + file.getCanonicalFile().equals(sameFile.getCanonicalFile()));
        System.out.println("abs ends:     " + sameFile.getAbsolutePath().endsWith("course-data/../course-data/lessons.txt"));

        File missing = new File("nope.txt");
        System.out.println("missing length: " + missing.length() + ", lastModified: " + missing.lastModified());
    }
}

Output (on Linux or macOS):

mkdir: true, again: false
getName:      lessons.txt
getPath:      course-data/lessons.txt
getParent:    course-data
exists:       true, isFile: true, isDirectory: false
length:       22 bytes
canRead:      true, canWrite: true
equals:       false
canonical eq: true
abs ends:     true
missing length: 0, lastModified: 0

Path information (no disk access)

MethodReturns
getName()The last name in the path: lessons.txt
getPath()The path as it was given (with the platform separator)
getParent() / getParentFile()The parent part as a String / File, or null if there is none
getAbsolutePath() / getAbsoluteFile()The path prefixed with the working directory, without removing .. or .
getCanonicalPath() / getCanonicalFile()The absolute path with ./.. removed and symbolic links resolved (accesses the disk; throws IOException)
isAbsolute()Whether the path is absolute

equals compares the path text, so course-data/lessons.txt and course-data/../course-data/lessons.txt aren't equal even though they're the same file. The canonical forms are equal. getAbsolutePath() keeps the .. exactly as written; only getCanonicalPath() cleans it up. These correspond to Path.toAbsolutePath() and Path.toRealPath().

File-system information

MethodReturns
exists()Whether something exists at this path
isFile() / isDirectory()Whether it's a regular file / a folder
length()Size in bytes (22: 1. Variables + \n + 2. Loops + \n)
lastModified()Last modification time in milliseconds since the epoch
canRead() / canWrite() / canExecute()Whether the current process has that access
isHidden()Whether the file is hidden (name starts with . on Unix, hidden attribute on Windows)

Look at the last line of the output: for a file that doesn't exist, length() and lastModified() return 0 instead of failing. 0 is also the length of a genuinely empty file, so these methods can't distinguish "empty" from "missing" from "unreadable". Files.size and Files.getLastModifiedTime throw NoSuchFileException in that case instead.

Creating Folders and Listing Contents

import java.io.*;
import java.util.Arrays;

public class F2 {
    public static void main(String[] args) throws IOException {
        File root = new File("media");
        System.out.println("mkdirs: " + new File(root, "images/2026").mkdirs());
        for (String n : new String[] {"logo.png", "banner.jpg", "notes.txt"}) {
            new File(root, n).createNewFile();
        }

        String[] names = root.list();
        Arrays.sort(names);
        System.out.println("list:       " + Arrays.toString(names));

        File[] images = root.listFiles((d, name) -> name.endsWith(".png") || name.endsWith(".jpg"));
        Arrays.sort(images);
        for (File f : images) System.out.println("image:      " + f.getPath());

        File[] dirs = root.listFiles(File::isDirectory);
        System.out.println("subfolders: " + dirs.length);

        System.out.println("listFiles on a file: " + new File(root, "notes.txt").listFiles());
        System.out.println("listFiles on missing: " + new File("ghost").listFiles());
    }
}

Output:

mkdirs: true
list:       [banner.jpg, images, logo.png, notes.txt]
image:      media/banner.jpg
image:      media/logo.png
subfolders: 1
listFiles on a file: null
listFiles on missing: null
  • mkdir() creates one folder and returns false if it already exists or its parent is missing. mkdirs() creates all missing parent folders too, like Files.createDirectories. Both return false on failure without saying why.
  • list() returns the names (String[]) of the folder's entries; listFiles() returns them as File objects. Both list only the folder's direct entries, and the order is not guaranteed, so the example sorts the results.
  • listFiles(FilenameFilter) filters by the parent folder and the name — the lambda (d, name) -> ... keeps images. listFiles(FileFilter) receives each entry as a File; the method reference File::isDirectory keeps only subfolders. Both interfaces have a single method, so lambdas and method references work.
  • listFiles() returns null — not an empty array — when the path isn't a folder, doesn't exist, or can't be read. Code like for (File f : dir.listFiles()) throws NullPointerException in those cases. Always check for null, as the practical example below does. Files.list throws a descriptive exception instead (NotDirectoryException, NoSuchFileException, AccessDeniedException).

Renaming, Permissions and Converting to Path

import java.io.*;
import java.nio.file.*;

public class F3 {
    public static void main(String[] args) throws IOException {
        File draft = new File("draft.md");
        draft.createNewFile();
        File published = new File("published.md");

        System.out.println("renameTo: " + draft.renameTo(published));
        System.out.println("draft exists: " + draft.exists() + ", published exists: " + published.exists());
        System.out.println("renameTo missing source: " + new File("ghost.md").renameTo(new File("x.md")));

        System.out.println("setReadOnly: " + published.setReadOnly() + ", canWrite: " + published.canWrite());
        System.out.println("setWritable: " + published.setWritable(true) + ", canWrite: " + published.canWrite());

        Path p = published.toPath();
        File back = p.toFile();
        System.out.println("toPath: " + p + ", back: " + back + ", size via Files: " + Files.size(p));
        System.out.println("delete: " + published.delete());
    }
}

Output (as a normal, non-administrator user):

renameTo: true
draft exists: false, published exists: true
renameTo missing source: false
setReadOnly: true, canWrite: false
setWritable: true, canWrite: true
toPath: published.md, back: published.md, size via Files: 0
delete: true
  • renameTo(dest) renames or moves the file and returns true on success. Its behaviour is explicitly platform-dependent: it may fail when the destination exists, when moving between file systems or disks, or when the file is open on Windows — always returning only false. A File object is immutable, so after a successful rename draft still refers to the old (now non-existent) name. Files.move is the reliable replacement, with clear exceptions and options like REPLACE_EXISTING and ATOMIC_MOVE.
  • setReadOnly(), setWritable(), setReadable() and setExecutable() change permissions and return whether it worked. A process running as root (or an administrator on Windows) can write to read-only files anyway, so in that case canWrite() still returns true.
  • delete() returns true if the file or empty folder was deleted (see the Delete Files lesson for why the boolean is a weakness).
  • toPath() and Path.toFile() convert between the two APIs, so you can use Files methods on a File you received from older code.

Disk Space and Roots

File also exposes information about the file system that contains a path:

File dataDir = new File("/srv/shop/uploads");
long usable = dataDir.getUsableSpace();   // bytes available to this JVM
long total  = dataDir.getTotalSpace();    // size of the partition
long free   = dataDir.getFreeSpace();     // unallocated bytes (may include space reserved for root)

File[] roots = File.listRoots();          // "/" on Unix; "C:\", "D:\", ... on Windows

getUsableSpace() is the one to use for decisions such as "is there room to save this upload?", because it accounts for space the operating system reserves. These methods return 0 if the path doesn't exist. The NIO equivalent is Files.getFileStore(path).getUsableSpace(), which throws an exception for a missing path instead.

File Compared with Path and Files

Taskjava.io.Filejava.nio.file
Represent a locationnew File("a/b.txt")Path.of("a", "b.txt")
Check existencefile.exists()Files.exists(path)
Sizefile.length() (0 if missing)Files.size(path) (throws if missing)
Create a filefile.createNewFile() → booleanFiles.createFile(path) → throws if it exists
Create foldersfile.mkdirs() → booleanFiles.createDirectories(path)
List a folderfile.listFiles() → may return nullFiles.list(path) → stream, throws on error
Rename / movefile.renameTo(dest) → boolean, platform-dependentFiles.move(src, dest, options...)
Deletefile.delete() → booleanFiles.delete(path) / Files.deleteIfExists(path)
Read whole text fileNeeds a reader and a loopFiles.readString(path)
Symbolic links, attributes, permissionsVery limitedFull support
Error detailsUsually just falseSpecific exception types with the path

The core problem with File is the boolean results: when something fails, you can't tell why, and if you ignore the return value, you can't even tell that it failed. Path and Files were designed to fix exactly this. Use File when an API requires it and convert with toPath() for everything else.

Practical Example: Disk Usage Report

This program calculates how much space a website folder uses, broken down by file type — the kind of check you'd run before deploying a site or when a hosting quota is nearly full. It uses File recursion, as much existing code does, and handles the null that listFiles() can return.

import java.io.*;
import java.util.*;

public class Usage {
    static long folderSize(File dir, Map<String, Long> byExtension) {
        File[] entries = dir.listFiles();
        if (entries == null) {
            System.out.println("cannot list " + dir);
            return 0;
        }
        long total = 0;
        for (File f : entries) {
            if (f.isDirectory()) {
                total += folderSize(f, byExtension);
            } else {
                String name = f.getName();
                int dot = name.lastIndexOf('.');
                String ext = dot > 0 ? name.substring(dot + 1).toLowerCase() : "(none)";
                byExtension.merge(ext, f.length(), Long::sum);
                total += f.length();
            }
        }
        return total;
    }

    static String human(long bytes) {
        if (bytes < 1024) return bytes + " B";
        if (bytes < 1024 * 1024) return String.format("%.1f KB", bytes / 1024.0);
        return String.format("%.1f MB", bytes / (1024.0 * 1024));
    }

    public static void main(String[] args) throws IOException {
        File site = new File("site");
        new File(site, "img").mkdirs();
        new File(site, "css").mkdirs();
        write(new File(site, "index.html"), 4_200);
        write(new File(site, "about.html"), 2_900);
        write(new File(site, "css/main.css"), 18_500);
        write(new File(site, "img/hero.JPG"), 1_450_000);
        write(new File(site, "img/logo.png"), 36_000);
        write(new File(site, "LICENSE"), 1_070);

        Map<String, Long> byExt = new TreeMap<>();
        long total = folderSize(site, byExt);
        byExt.forEach((ext, size) -> System.out.printf("%-7s %10s%n", ext, human(size)));
        System.out.printf("%-7s %10s%n", "total", human(total));
    }

    static void write(File f, int size) throws IOException {
        try (FileOutputStream out = new FileOutputStream(f)) {
            out.write(new byte[size]);
        }
    }
}

Output:

(none)      1.0 KB
css        18.1 KB
html        6.9 KB
jpg         1.4 MB
png        35.2 KB
total       1.4 MB

How it works:

  1. Sample files. write creates files of a chosen size by writing that many zero bytes with a FileOutputStream (covered in the FileOutputStream lesson), so the sizes are predictable.
  2. Recursion. folderSize lists a folder; for each subfolder it calls itself, and for each file it adds length() to the total. The recursion naturally follows the tree of any depth.
  3. null check. If a folder can't be listed (for example, no read permission), listFiles() returns null. The method reports it and counts it as 0 instead of crashing the whole report.
  4. Extensions. The extension is lowercased so hero.JPG is counted under jpg. A file without a dot (LICENSE) is grouped as (none).
  5. Map.merge adds each file's size to its extension's running total, starting a new entry when the extension is seen for the first time. A TreeMap keeps the report sorted.
  6. Formatting. human converts bytes to KB/MB using 1,024 as the unit: 4,200 + 2,900 = 7,100 bytes is 6.9 KB, and the 1,450,000-byte image is about 1.4 MB.

One caution about this recursive approach: isDirectory() follows symbolic links, so a link pointing to a parent folder would make the recursion loop forever (until a StackOverflowError). Files.walk and Files.walkFileTree don't follow links by default and detect cycles when you ask them to follow links — another reason they're preferred for new code. The same report written with NIO appears in the Directory Handling lesson.

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 Class and get answers drawn from it.

Signed-in readers only.