1. Introduction
In this article, we are going to present how to convert File
into Path
in Java. A Path is an object that may be used to locate a file in a file system. This article will cover the two most common solutions from Java 7+.
2. Convert File
to Path
using toPath()
method
Path
object was introduced in Java 7. In this version of JDK, we can get the Path
using the File.toPath()
method.
package com.frontbackend.java.io.path;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
public class ConvertFileToPath {
public static void main(String[] args) throws IOException {
File file = new File("/tmp/test.txt");
Path path = file.toPath();
System.out.println(path.toString());
}
}
3. Convert File
to Path
using Paths
object
The Paths
object is a dedicated class that consists exclusively of static methods that return a Path
.
In the following example code we used Paths.get(...)
method to convert File
to Path
:
package com.frontbackend.java.io.path;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ConvertFileToPathUsingPaths {
public static void main(String[] args) {
File file = new File("/tmp/test.txt");
Path path = Paths.get(file.toURI());
System.out.println(path.toString());
}
}
4. Conclusion
In this article, we presented ways to convert File
to Path
. We use the Path
object to locate a file in the file system. Bear in mind that Path
is only available for Java 7+ programs.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}