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

- 657
- 2
- 6
- 8
-
Duplicate? - https://stackoverflow.com/a/26658436/384674 – Betlista Feb 05 '18 at 12:07
-
just call toFile() on Path object – Ramanlfc Feb 05 '18 at 12:09
-
@Betlista The referenced post is not a duplicate. It is a broad question discussing about which API chooses between Pah and File. There exists maybe a real duplicate. Please refer that if you found it. – davidxxx Feb 05 '18 at 12:15
-
@davidxxx I kindly disagree, in first answer it says "And if you ever need a File object for legacy, just call Path#toFile()", with a small effort it can be found easily... – Betlista Feb 05 '18 at 12:18
-
@Betlista This point is a side note about compatibility between the two APIs. I don't think that it is an effort question. Duplicates means that the question has duplicate(s). In many complete answers, you can find information that addresses multiple questions. So I don't think that it is relevant. Don't you think that reading so many lines and posts to know how to convert a Path to File is not efficient ? – davidxxx Feb 05 '18 at 12:24
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 thisPath
is associated with the default provider, then this method is equivalent to returning aFile
object constructed with theString
representation of this path.If this path was created by invoking the
File
toPath
method then there is no guarantee that theFile
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 resultingPath
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
.

- 125,838
- 23
- 214
- 215