Get java.nio.file.Path object from java.io.File

2019-03-09 10:04发布

Is it possible to get a Path object from a java.io.File?

I know you can convert a path to a file using toFile() method, but I couldn't find the opposite conversion. Is there a way to do this in Java 6 or lower?

4条回答
霸刀☆藐视天下
2楼-- · 2019-03-09 10:51

Yes, you can get it from the File object by using File.toPath(). Keep in mind that this is only for Java 7+. Java versions 6 and below do not have it.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-03-09 10:51

You likely want File.toPath().

查看更多
乱世女痞
4楼-- · 2019-03-09 10:54

From the documentation:

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.

(emphasis mine)

So, for toFile:

Returns a File object representing this path.

And toPath:

Returns a java.nio.file.Path object constructed from the this abstract path.

查看更多
孤傲高冷的网名
5楼-- · 2019-03-09 11:05

As many have suggested, JRE v1.7 and above has File.toPath();

File yourFile = ...;
Path yourPath = yourFile.toPath();

On Oracle's jdk 1.7 documentation which is also mentioned in other posts above, the following equivalent code is described in the description for toPath() method, which may work for JRE v1.6;

File yourFile = ...;
Path yourPath = FileSystems.getDefault().getPath(yourFile.getPath());
查看更多
登录 后发表回答