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:
xxxxxxxxxx
1
import java.io.File;
2
import java.nio.file.Path;
3
4
public class FileToPathExample {
5
6
public static void main(String[] args) {
7
8
File file = new File("C:\\examples");
9
10
Path path = file.toPath();
11
12
// ...
13
}
14
}
Before java 1.7 we could convert File
to Path
like this:
xxxxxxxxxx
1
import java.io.File;
2
import java.nio.file.FileSystems;
3
import java.nio.file.Path;
4
5
public class FileToPathExample2 {
6
7
public static void main(String[] args) {
8
9
File file = new File("C:\\examples");
10
11
Path path = FileSystems.getDefault().getPath(file.getPath());
12
13
// ...
14
}
15
}