Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert object from java.nio.file.Path to java.io.File [duplicate]

Tags:

java

I would like to know if it is possible somehow to convert an object that is defined as java.nio.file.Path to java.io.File

like image 944
Ramon De Les Olives Avatar asked Feb 05 '18 12:02

Ramon De Les Olives


People also ask

How to convert file Path to file in Java?

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

How to duplicate a file in Java?

If you are working on Java 7 or higher, you can use Files class copy() method to copy file in java. It uses File System providers to copy the files.


1 Answers

Both java.nio.file.Path and java.io.File classes provides a way to pass from the one to the other.

1) Invoking toFile() on a Path object returns a File representing it.

Path.toFile() javadoc :

Returns a File object representing this path. Where this Path is associated with the default provider, then this method is equivalent to returning a File object constructed with the String representation of this path.

If this path was created by invoking the File toPath method then there is no guarantee that the File object returned by this method is equal to the original File.

2) Reversely, invoking toPath() on a File object returns a Path representing it.

File.toPath() javadoc :

Returns a java.nio.file.Path object constructed from the this abstract path. The resulting Path is associated with the default-filesystem.

The first invocation of this method works as if invoking it were equivalent to evaluating the expression:

FileSystems.getDefault().getPath(this.getPath());

Subsequent invocations of this method return the same Path.

like image 86
davidxxx Avatar answered Sep 30 '22 16:09

davidxxx