是否有可能从java.io.File中获得Path对象?
我知道您可以使用toFile()方法将路径转换为文件,但我找不到相反的转换。在Java 6或更低版本中有办法做到这一点吗?
是否有可能从java.io.File中获得Path对象?
我知道您可以使用toFile()方法将路径转换为文件,但我找不到相反的转换。在Java 6或更低版本中有办法做到这一点吗?
从文档中可以看到:
Paths associated with the default provider are generally interoperable with the java.io.File class. Paths created by other providers are unlikely to be interoperable with the abstract path names represented by java.io.File. The toPath method may be used to obtain a Path from the abstract path name represented by a java.io.File object. The resulting Path can be used to operate on the same file as the java.io.File object. In addition, the toFile method is useful to construct a File from the String representation of a Path.
(强调我的)
因此,对于toFile:
返回表示此路径的File对象。
和toPath:
返回由此抽象路径构造的java.nio.file.Path对象。
正如许多人所建议的,JRE v1.7及以上版本有File.toPath();
File yourFile = ...;
Path yourPath = yourFile.toPath();
在Oracle的jdk 1.7文档中,上面的其他文章也提到过,下面的等效代码在toPath()方法的描述中描述,它可能适用于JRE v1.6;
File yourFile = ...;
Path yourPath = FileSystems.getDefault().getPath(yourFile.getPath());