Java IO Tutorial

Java – Convert File to Path

This article shows how to convert a File to a Path in Java.

java.io.File => java.nio.file.Path


// Convert File to Path
File file = new File("/home/mkyong/test/file.txt");
Path path = file.toPath();

java.nio.file.Path => java.io.File


// Convert Path to File
Path path = Paths.get("/home/mkyong/test/file.txt");
File file = path.toFile();

1. Convert File to Path

In Java, we can use file.toPath() to convert a File into a Path.

FileToPath.java

package com.mkyong.io.howto;

import java.io.File;
import java.nio.file.Path;

public class FileToPath {

    public static void main(String[] args) {

        File file = new File("/home/mkyong/test/file.txt");

        // Java 1.7, convert File to Path
        Path path = file.toPath();

        System.out.println(path);

    }
}

2. Convert Path to File

In Java, we can use path.toFile() to convert a Path into a File.

PathToFile.java

package com.mkyong.io.howto;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathToFile {

    public static void main(String[] args) {

        Path path = Paths.get("/home/mkyong/test/file.txt");

        // Convert Path to File
        File file = path.toFile();

        System.out.println(file);

    }
}

Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-io

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments