How to convert File to Path and Path to File in Java
Java introduced the Path interface in Java 7 (1.7).
It is part of the Non-blocking IO (java.nio
) package which was introduced with the J2SE 1.4 release to complement the standard I/O API.
The File class is part of the standard I/O API (java.io
).
As Java programmers we will often need to convert from one to the other.
The following sections show you how.
How to convert File to Path
The File
class has a method toPath()
that returns a Path
object representing the path of the file.
File file = new File("/path/to/file.txt");
Path path = file.toPath();
How to convert Path to File
The Path
interface has a method toFile()
that returns a File
object representing the path of the file.
Path path = Paths.get("/path/to/file.txt");
File file = path.toFile();