Languages
[Edit]
EN

Java - convert File to Path

2 points
Created by:
JustMike
3533

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());
        
        // ...
    }
}

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.