EN
Java - convert File to Path
2
points
In this short article, I would like to share how to get Path from File in java. It is quite easy, but is a common problem :)
To solve this problem we just need to call file.toPath() method on File object. Note that this method was added in java 1.7.
Full working example:
import java.io.File;
import java.nio.file.Path;
public class FileToPathExample {
public static void main(String[] args) {
File file = new File("C:\\examples");
Path path = file.toPath();
// ...
}
}
Before java 1.7
Before java 1.7 we could convert File to Path like this:
import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Path;
public class FileToPathExample2 {
public static void main(String[] args) {
File file = new File("C:\\examples");
Path path = FileSystems.getDefault().getPath(file.getPath());
// ...
}
}