CodeGym /Courses /JAVA 25 SELF /File, Path, and Files classes: overview and object creati...

File, Path, and Files classes: overview and object creation

JAVA 25 SELF
Level 35 , Lesson 1
Available

1. Class File: how it all started

Even though we’ve established that the File class is better avoided in new projects, there are still many legacy systems where it’s used. Therefore, it’s important to understand it and be able to work with it. The File class is the old way to represent a file or directory on disk. But don’t confuse things: a File object is not the file itself, but just a “pointer”/path descriptor. For example, the expression File f = new File("hello.txt"); does not create a file on disk — you just described a path.

How to create a File object?

import java.io.File;

public class FileDemo {
    public static void main(String[] args) {
        File file = new File("example.txt"); // relative path
        File folder = new File("mydir");     // directory

        System.out.println("Absolute path: " + file.getAbsolutePath());
        System.out.println("Does the file exist? " + file.exists());
        System.out.println("Is it a file? " + file.isFile());
        System.out.println("Is it a directory? " + folder.isDirectory());
    }
}

Important to remember:
Creating a File object does not create a file on disk. It’s just a “shortcut”. For the file to actually appear, you must explicitly initiate creation (for example, write data or call file.createNewFile()).

Key methods of the File class

  • exists() — checks whether the file/directory exists.
  • isFile() — is it a file (not a folder)?
  • isDirectory() — is it a directory?
  • getAbsolutePath() — get the absolute path.
  • length() — file size in bytes.
  • getName() — file or folder name.
  • delete() — delete a file/directory (if empty).

Example: print file info

File file = new File("example.txt");
System.out.println("Name: " + file.getName());
System.out.println("Path: " + file.getAbsolutePath());
System.out.println("Size: " + file.length() + " bytes");
System.out.println("Exists? " + file.exists());

2. Class Path: a modern view of files

Path is part of the newer file API (NIO.2, since Java 7). It’s an abstraction of a path to a file/directory, and the path can be not only on a local disk but also, for example, inside a ZIP archive or on a remote resource (if the appropriate provider is available).

If File is an old paper map, then Path is a GPS navigator.

How to create a Path object?

import java.nio.file.Path;
import java.nio.file.Paths;

public class PathDemo {
    public static void main(String[] args) {
        Path path1 = Paths.get("example.txt"); // relative path
        Path path2 = Paths.get("folder", "file.txt"); // join path parts

        System.out.println("Path 1: " + path1.toAbsolutePath());
        System.out.println("Path 2: " + path2.toAbsolutePath());
    }
}

Plus: you don’t need to worry about separators. Paths.get will choose the correct format for your OS.

Conversion between File and Path

  • FilePath: file.toPath()
  • PathFile: path.toFile()
File file = new File("test.txt");
Path path = file.toPath();

Path anotherPath = Paths.get("data.txt");
File anotherFile = anotherPath.toFile();

Working with paths: resolve, relativize, normalize

Joining paths (resolve)

Path dir = Paths.get("myfolder");
Path file = dir.resolve("notes.txt"); // myfolder/notes.txt
System.out.println(file); // myfolder/notes.txt

Relative path (relativize)

Path pathA = Paths.get("folderA/file1.txt");
Path pathB = Paths.get("folderA/subfolder/file2.txt");
Path relative = pathA.relativize(pathB);
System.out.println(relative); // ../subfolder/file2.txt

Path normalization (normalize)

Path messy = Paths.get("folder/../folder/file.txt");
Path clean = messy.normalize();
System.out.println(clean); // folder/file.txt

Example: build a path to a file

Path home = Paths.get(System.getProperty("user.home"));
Path docs = home.resolve("Documents");
Path myFile = docs.resolve("myfile.txt");
System.out.println("File path: " + myFile.toAbsolutePath());

3. Class Files: your Swiss Army knife

The Files class from the java.nio.file package is a utility set of static methods for working with files and directories on top of Path. It can do almost everything: check existence, create/delete, read/write, copy/move, get attributes, and walk a directory tree.

Key methods of the Files class

  • Files.exists(path) — checks whether the file/directory exists.
  • Files.isDirectory(path) — is it a directory?
  • Files.size(path) — file size.
  • Files.createFile(path) — create a file.
  • Files.createDirectory(path) — create a directory.
  • Files.delete(path) — delete a file/directory.
  • Files.copy(src, dest) — copy a file.
  • Files.move(src, dest) — move/rename.
  • Files.getLastModifiedTime(path) — last modified time.
  • Files.readAllBytes(path) — read the whole file into a byte array.
  • Files.readAllLines(path) — read all lines of a text file.
  • Files.write(path, bytes) — write bytes to a file.

Example: check a file

import java.nio.file.*;

public class FilesDemo {
    public static void main(String[] args) {
        Path path = Paths.get("example.txt");

        System.out.println("Does the file exist? " + Files.exists(path));
        System.out.println("Is it a directory? " + Files.isDirectory(path));

        if (Files.exists(path)) {
            try {
                System.out.println("File size: " + Files.size(path) + " bytes");
            } catch (Exception e) {
                System.out.println("Error getting size: " + e.getMessage());
            }
        }
    }
}

4. Practice: creating objects and printing properties

Create objects for a file and a directory

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CompareDemo {
    public static void main(String[] args) {
        // Old approach
        File oldFile = new File("test.txt");
        File oldDir = new File("mydir");

        // New approach
        Path newFile = Paths.get("test.txt");
        Path newDir = Paths.get("mydir");

        System.out.println("=== File API ===");
        System.out.println("File: " + oldFile.getAbsolutePath());
        System.out.println("Exists? " + oldFile.exists());
        System.out.println("Is it a file? " + oldFile.isFile());
        System.out.println("Is it a directory? " + oldDir.isDirectory());

        System.out.println("\n=== Path API ===");
        System.out.println("File: " + newFile.toAbsolutePath());
        System.out.println("Exists? " + java.nio.file.Files.exists(newFile));
        System.out.println("Is it a file? " + java.nio.file.Files.isRegularFile(newFile));
        System.out.println("Is it a directory? " + java.nio.file.Files.isDirectory(newDir));
    }
}

Print file properties

import java.nio.file.*;

public class FileProperties {
    public static void main(String[] args) {
        Path path = Paths.get("test.txt");

        System.out.println("Absolute path: " + path.toAbsolutePath());
        System.out.println("File name: " + path.getFileName());
        System.out.println("Parent directory: " + path.getParent());

        if (Files.exists(path)) {
            try {
                System.out.println("Size: " + Files.size(path) + " bytes");
                System.out.println("Last modified: " + Files.getLastModifiedTime(path));
            } catch (Exception e) {
                System.out.println("Error getting information: " + e.getMessage());
            }
        } else {
            System.out.println("File not found.");
        }
    }
}

5. Comparison: File vs Path/Files

Capability File (java.io) Path + Files (java.nio.file)
Path representation Local disk only Local disk, ZIP, network resources
Joining paths Manual concatenation with slashes Convenient via resolve
Checking existence exists() Files.exists(path)
Reading/writing contents No Yes (Files.readAll..., Files.write)
Retrieving attributes Basic (length(), lastModified()) Extended attributes and views
Compatibility All Java versions Java 7 and later
Handling symlinks Limited Full support

In short: when to use what?

  • For new projects — use Path and Files.
  • To maintain legacy code — you’ll sometimes have to work with File.

6. Useful nuances

Relative and absolute paths

A relative path is a path relative to the current working directory; an absolute path is the full path from the root of the file system.

Path relative = Paths.get("data", "file.txt");
Path absolute = relative.toAbsolutePath();
System.out.println("Absolute path: " + absolute);

Cross-platform considerations

Path and Files respect OS specifics (separators, encodings, etc.). Don’t write paths by hand like "C:\\folder\\file.txt" — use Paths.get and resolve.

Conversion between File and Path

If you have old code using File, it’s easy to switch to the new API:

File legacy = new File("legacy.txt");
Path modern = legacy.toPath();
if (Files.exists(modern)) {
    // Now you can use all NIO.2 capabilities
}

Checking if a file exists

Path path = Paths.get("notes.txt");
if (Files.exists(path)) {
    System.out.println("File found!");
} else {
    System.out.println("File does not exist.");
}

7. Mini‑practice: create and check a file and a directory

import java.nio.file.*;

public class MiniPractice {
    public static void main(String[] args) throws Exception {
        Path dir = Paths.get("demo_dir");
        Path file = dir.resolve("hello.txt");

        // Create the directory if it doesn't exist
        if (!Files.exists(dir)) {
            Files.createDirectory(dir);
            System.out.println("Directory created: " + dir.toAbsolutePath());
        }

        // Create the file if it doesn't exist
        if (!Files.exists(file)) {
            Files.createFile(file);
            System.out.println("File created: " + file.toAbsolutePath());
        }

        // Print properties
        System.out.println("Does the file exist? " + Files.exists(file));
        System.out.println("Is it a file? " + Files.isRegularFile(file));
        System.out.println("Size: " + Files.size(file) + " bytes");

        // Delete the file and the directory (optional)
        Files.delete(file);
        Files.delete(dir);
        System.out.println("File and directory deleted.");
    }
}

8. Common mistakes when working with File/Path/Files

Error #1: Confusing File and Path. Many beginners try to use Files methods with a File object. Remember: Files.* works with Path. If you have a File, first call file.toPath().

Error #2: Expecting that creating a File or Path object creates a file. A path object is a shortcut, not a real file. To create one, use Files.createFile(path) or write data.

Error #3: Manually building paths as strings. Don’t write "folder/file.txt" or "folder\\file.txt". Use Paths.get(...) and resolve(...). It’s safer and cross-platform.

Error #4: Ignoring exceptions. File operations throw IOException and other exceptions. Handle them with try-catch or rethrow them (throws).

Error #5: Checking via File.exists(), then working via Path. Try to stick to one style: if you start with Path, use Files.exists(path) and other Files methods.

1
Task
JAVA 25 SELF, level 35, lesson 1
Locked
Where are the treasures? Checking the game assets directory 🎮
Where are the treasures? Checking the game assets directory 🎮
1
Task
JAVA 25 SELF, level 35, lesson 1
Locked
Building the project: full path to the "main" file 🏗️
Building the project: full path to the "main" file 🏗️
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION