Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Files and I/O

Java Files and Directories with NIO.2: Path and Files

Path.of("invoices", "2026", "inv-101.pdf") is only an address: getFileName, getParent and resolve work, but nothing is on disk. Files.createDirectories and createFile make an order file and delete removes it, Files.walk finds 4 .java files, and os.name tells Windows from Linux.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Files and I/O

What you will learn

  • Build an operating-system-independent path with Path.of and read its parts
  • Create and delete folders and files with the Files class
  • List every file below a folder with Files.walk
  • Find the operating system and its path separator

Before you start

  • Java try-with-resources and clean error handling
  • Java streams I: filter, map and reduce

Programs often have to deal with files, and to reach a file you first need its path. NIO.2 (the java.nio.file package) gives you two tools: Path, an address, and Files, which does the work on disk. The outputs below come from a Windows machine, so they show backslashes; on macOS or Linux you'll see forward slashes.

A path is only an address

package org.studyeasy.s07l01;

import java.nio.file.Files;
import java.nio.file.Path;

public class Ex01_PathParts {
    public static void main(String[] args) {
        // A Path is only an address, nothing is created
        Path invoice = Path.of("invoices", "2026", "inv-101.pdf");
        System.out.println("Path:      " + invoice);
        System.out.println("File name: " + invoice.getFileName());
        System.out.println("Parent:    " + invoice.getParent());
        System.out.println("Parts:     " + invoice.getNameCount());

        // resolve: add one more name to the end of a path
        Path receipt = invoice.getParent().resolve("rcpt-101.pdf");
        System.out.println("Receipt:   " + receipt);
        System.out.println("On disk?   " + Files.exists(receipt));
    }
}
Path:      invoices\2026\inv-101.pdf
File name: inv-101.pdf
Parent:    invoices\2026
Parts:     3
Receipt:   invoices\2026\rcpt-101.pdf
On disk?   false
Path.of with three names: invoices, 2026, inv-101.pdf. getParent picks the first two boxes, invoices and 2026. getFileName picks the last box, inv-101.pdf. getNameCount counts three boxes. resolve on the parent adds rcpt-101.pdf as a new last box. invoices2026inv-101.pdf rcpt-101.pdf getParent() getFileName() getParent().resolve(...) getNameCount() = 3. Nothing here exists on disk until Files creates it.
A Path holds names; Java joins them with the right separator for your system.

The separator differs between Windows, Linux and macOS, so you give Path.of the names and Java joins them correctly. This is a relative path: the invoices folder sits next to where the program runs. getFileName gives the last part, getParent everything before it, and getNameCount counts the parts. resolve adds a name to the end. A Path never creates anything, so Files.exists is false.

Make a folder and a file, then remove it

Path folder = Path.of("orders", "2026");
Path order = folder.resolve("order-1042.txt");

// creates the folder and any missing parent folders
Files.createDirectories(folder);
System.out.println("Folder exists: " + Files.exists(folder));

// creates an empty file; its folder must exist
Files.createFile(order);
System.out.println("Created:       " + order);
System.out.println("File exists:   " + Files.exists(order));

Files.delete(order);
// the file is already gone: no error here
Files.deleteIfExists(order);
System.out.println("After delete:  " + Files.exists(order));
Folder exists: true
Created:       orders\2026\order-1042.txt
File exists:   true
After delete:  false

createDirectories makes orders and the 2026 folder inside it, and doesn't complain if they already exist. createFile makes an empty file. delete removes it, and deleteIfExists does nothing if it's already gone. These methods throw the checked IOException, so main declares throws.

When something is offResult
createDirectories, folder already thereno error
createFile, file already existsFileAlreadyExistsException
createFile, folder missingNoSuchFileException
a second deleteNoSuchFileException

Every file below a folder

// walk: every folder and file below src
try (Stream<Path> tree = Files.walk(Path.of("src"))) {
    List<Path> javaFiles = tree
            .filter(p -> p.toString().endsWith(".java"))
            .sorted().toList();
    for (Path file : javaFiles) {
        System.out.println(file.getFileName() + " -> " + file);
    }
    System.out.println("Java files: " + javaFiles.size());
}
Ex01_PathParts.java -> src\main\java\org\studyeasy\s07l01\Ex01_PathParts.java
Ex02_CreateDelete.java -> src\main\java\org\studyeasy\s07l01\Ex02_CreateDelete.java
Ex03_WalkFolder.java -> src\main\java\org\studyeasy\s07l01\Ex03_WalkFolder.java
Ex04_OsCheck.java -> src\main\java\org\studyeasy\s07l01\Ex04_OsCheck.java
Java files: 4

When you know a parent folder but not what's inside, Files.walk returns a stream of every folder and file below it, here ten paths: six folders and four files. The filter keeps the four ending in .java. The stream holds the folder open, so it goes in try-with-resources to be closed. A folder that doesn't exist gives NoSuchFileException.

Which system, which separator

// os.name is "Windows 11", "Mac OS X", "Linux" ...
String os = System.getProperty("os.name");
boolean windows = os.toLowerCase().contains("win");

// backslash on Windows, forward slash on macOS and Linux
String sep = FileSystems.getDefault().getSeparator();

// Path.of picks the separator, so no gluing by hand
Path report = Path.of("reports", "2026", "march.csv");
OS:        Windows 11
Windows?   true
Separator: \
Report:    reports\2026\march.csv

The OS and separator lines will differ on your machine. You rarely need the separator yourself, because Path.of picks it for you.

Recap

CallWhat it does
Path.of("a", "b", "c.txt")an address; nothing on disk
getFileName, getParent, resolveread or extend the path
Files.createDirectories, createFilemake folders and files
Files.delete, deleteIfExistsremove a file
Files.walkevery path below a folder

A Path is only an address; Files does the work. Next: putting text in those files, in reading and writing text files.

Keep going in Java · 77 of 79

Previous
@Async, Named TaskExecutors and Structured Concurrency in Spring Boot
Next post
Reading and Writing Text Files in Java
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Reading and Writing Text Files in Java

Files.readString reads tasks.txt in one call and readAllLines splits it into three tasks. writeString makes a shopping list that Files.lines filters to 2 items starting with B, a BufferedWriter writes an invoice, a Scanner totals 257, and Café is 4 characters but 5 bytes.

Java Structured Data: Reading and Writing JSON and CSV

Two Student records, Emma Clark with 91 in Java and Liam Brown with 78 in SQL, saved two ways. Jackson's ObjectMapper writes them to students.json and reads them back in one call each; plain Java writes students.csv with a header and reads it back by splitting at the commas.

On this page

  • A path is only an address
  • Make a folder and a file, then remove it
  • Every file below a folder
  • Which system, which separator
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.