[NIO.2] 第五篇 Path 对象的转换

本文中,你将可以看到如何将 Path 对象转换为其它对象。本文所有例子都是基于下面的 Path 对象:

Path path = Paths.get("/rafaelnadal/tournaments/2009", "BNP.txt");


[b][size=x-large]将 Path 转换为 String[/size][/b]

可以直接使用 Path.toString() 方法进行转换:

//output: \rafaelnadal\tournaments\2009\BNP.txt
String path_to_string = path.toString();
System.out.println("Path to String: " + path_to_string);


[b][size=x-large]将 Path 转换为 URI[/size][/b]

可以调用 Path.toURI() 方法转换为浏览器可识别的 URI 格式,输出的字符串可以直接输入到浏览器的地址栏中。

//output: file:///C:/rafaelnadal/tournaments/2009/BNP.txt
URI path_to_uri = path.toUri();
System.out.println("Path to URI: " + path_to_uri);


[b][size=x-large]将相对路径转换为绝对路径[/size][/b]

从相对路径得到绝对路径是一个经常遇到的问题。NIO.2 中可以调用 toAbsolutePath() 来达到这个目的(如果本身就是绝对路径,那么将会返回原有的 path 对象)

//output: C:\rafaelnadal\tournaments\2009\BNP.txt 
Path path_to_absolute_path = path.toAbsolutePath();
System.out.println("Path to absolute path: " + path_to_absolute_path.toString());


[b][size=x-large]将 Path 转换为真实路径[/size][/b]

调用 toRealPath() 方法可以返回一个已存在的文件的真实路径。如果使用不带参数的 toRealPath() 方法并且文件系统支持符号链接的话,这个方法会解析路径中的所有符号连接。如果你想忽略符号链接所链接的文件,而只需要处理符号链接本身的文件,可以传入 LinkOption.NOFOLLOW_LINKS 这个枚举常量作为参数。如果 Path 是相对路径,那么将返回绝对路径,如果 Path 对象中包含有冗余信息,那么冗余信息将会被清除,如果文件不存在或不可访问,那么将会抛出 IOException。
下面的代码将返回文件的真实路径,并且忽略符号链接:

import java.io.IOException;

//output: C:\rafaelnadal\tournaments\2009\BNP.txt
try {
Path real_path = path.toRealPath(LinkOption.NOFOLLOW_LINKS);
System.out.println("Path to real path: " + real_path);
} catch (NoSuchFileException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}

[b][size=x-large]
将 Path 转换为 File[/size][/b]

可以调用 Path 对象的 toFile() 方法转换为 File 对象。File 对象也提供了 toPath() 方法来进行相互转换。

//output: BNP.txt 
File path_to_file = path.toFile();

//output: \rafaelnadal\tournaments\2009\BNP.txt
Path file_to_path = path_to_file.toPath();
System.out.println("Path to file name: " + path_to_file.getName());
System.out.println("File to path: " + file_to_path.toString());


文章来源:[url]http://www.aptusource.org/2014/03/nio-2-convert-path-object/[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值