Languages
[Edit]
EN

Java - convert File to Path

2 points
Created by:
kaya31
526

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());

        // ...
    }
}
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java conversion

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join