Java - File Input Output Paths

Introduction

Path class represents a path in a file system such as a file, a directory, and a symbolic link.

Path is an interface in the java.nio.file package.

You work with Path interface using Paths class and Files class.

A path does not have to exist in a file system to create a Path object.

Files class performs the file I/O operations on a Path object.

Files class consists of all static methods.

Creating a Path Object

FileSystem object acts as a factory to create a Path object.

You can use the getPath() method of the FileSystem class to create a Path object.

The following code creates a Path object for file path C:\myData\Main.java on Windows:

Path p1 = FileSystems.getDefault().getPath("C:\\myData\\Main.java");

You can use separate path to the getPath() method when creating a Path object. Java uses appropriate platform-dependent file name separators.

The following statement creates a Path object to represent the C:\myData\Main.java path on Windows:

Path p2 = FileSystems.getDefault().getPath("C:", "myData", "Main.java");

Paths class creates a Path object from the components of a path string or a URI.

Paths.get() static method creates a Path object.

The following code creates Path objects to represent the same path, C:\myData\Main.java:

Path p3 = Paths.get("C:\\myData\\Main.java");
Path p4 = Paths.get("C:", "myData", "Main.java");

An empty path such as Paths.get("") refers to the default directory of the file system.

Related Topics