将对象从 java.nio.file.Path 转换为 java.io.File

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48622208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 10:07:42  来源:igfitidea点击:

Convert object from java.nio.file.Path to java.io.File

java

提问by Ramon De Les Olives

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

我想知道是否有可能以某种方式来转换被定义为对象java.nio.file.Path,以java.io.File

回答by davidxxx

Both java.nio.file.Pathand java.io.Fileclasses provides a way to pass from the one to the other.

java.nio.file.Pathjava.io.File类提供了一种方法以从一个到另一个传递。

1) Invoking toFile()on a Pathobject returns a Filerepresenting it.

1) 调用 toFile()一个Path对象会返回一个File表示它的对象。

Path.toFile()javadoc :

Path.toFile()文档:

Returns a Fileobject representing this path. Where this Pathis associated with the default provider, then this method is equivalent to returning a Fileobject constructed with the Stringrepresentation of this path.

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

返回File表示此路径的对象。如果 thisPath与默认提供程序相关联,则此方法等效于返回使用此路径FileString表示构造的对象。

如果此路径是通过调用该FiletoPath方法创建的,则无法保证File此方法返回的对象等于原始 File。

2) Reversely, invoking toPath()on a Fileobject returns a Pathrepresenting it.

2) 相反,调用toPath()一个File对象会返回一个Path表示它的对象。

File.toPath()javadoc :

File.toPath()文档:

Returns a java.nio.file.Pathobject constructed from the this abstract path. The resulting Pathis 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.

返回java.nio.file.Path从 this 抽象路径构造的对象。结果Path与默认文件系统相关联。

此方法的第一次调用就好像调用它等效于评估表达式:

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

此方法的后续调用返回相同的Path