Convert File to Path and Path to File in Java

In this tutorial will show you how to convert File to a Path and Path to a File Object in Java –

java.io.File into java.nio.file.Path

// Convert File to Path
File file = new File("C:\\Users\\codehelper\\test\\sample.txt");
Path path = file.toPath();

java.nio.file.Path into java.io.File

// Convert Path to File
Path path = Paths.get("C:\\Users\\codehelper\\test\sample.txt");
File file = path.toFile();

1. Convert File to Path in Java

In Java, you can convert File to Path using file.toPath()

package com.codehelp.java8.io;

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

public class CodeHelpFileToPath {

    public static void main(String[] args) {

        File file = new File("C:\\Users\\codehelper\\test\\sample.txt");

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

        System.out.println(path);

    }
}

Output :

C:\Users\codehelper\test\sample.txt

2. Convert Path to File in Java

In Java, you can convert File to Path using path.toFile()

package com.codehelp.java8.io;

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

public class CodeHelpPathToFile {

    public static void main(String[] args) {

        Path path = Paths.get("C:\\Users\\codehelper\\test\\sample.txt");

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

        System.out.println(file);

    }
}

 

References:

 

 

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.