Here we will see how to convert Path to File in java.

How to convert Path to File?

The Java Path interface provides to* methods to convert Path -> File.

Path.toFile():

The Path.toFile() converts java.nio.file.Path to java.io.File

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

public class PathToFile {
    public static void main(String[] args) throws Exception {
        Path path = Paths.get("/Users/chan8047/sample.txt");

        File file = path.toFile();

        if (file.exists()) {
            System.out.println("The File Existed");
        } else {
            System.out.println("The File does not exist");
        }
    }
}

Output:

The File Existed

File.toPath()

The File.toPath() method from File class is used to convert java.io.File to java.nio.file.Path

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

public class FileToPath {
    
    public static void main(String[] args) throws Exception {

        File file = new File("/Users/chan8047/sample.txt");

        Path path = file.toPath();

        System.out.println("path :: "+path);

    }
}

Output:

path :: /Users/chan8047/sample.txt

References:

Happy Learning 🙂