Path toFile() method in Java with Examples
Last Updated :
18 Jul, 2019
The toFile() method of java.nio.file.Path interface used to return a java.io.File object representing this path object. if this Path is associated with the default provider, then this method returns a java.io.File object constructed with the String representation of this path. If this path was created by invoking the java.io.File toPath method then there is no guarantee that the File object returned by this method is equal to the original File. This method throws UnsupportedOperationException if this Path is not associated with the default provider.
Syntax:
default File toFile()
Parameters: This method accepts nothing.
Return value: This method returns a java.io.File object representing this path.
Exception: This method throws UnsupportedOperationException if this Path is not associated with the default provider.
Below programs illustrate toFile() method:
Program 1:
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
public class GFG {
public static void main(String[] args)
{
Path path
= Paths.get( "D:\\Apps\\"
+ "NewTextDocument.txt" );
File file = path.toFile();
System.out.println( "File:" + file.toString()
+ " is readable "
+ file.canRead());
}
}
|
Output:
Program 2:
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
public class GFG {
public static void main(String[] args)
{
Path path = Paths.get( "D:\\temp\\"
+ "AmanSinghCV.docx" );
File file = path.toFile();
System.out.println( "File Name:"
+ file.getName());
}
}
|
Output:
References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#toFile()
Share your thoughts in the comments
Please Login to comment...