[NIO.2] Path 对象的转换_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > [NIO.2] Path 对象的转换

[NIO.2] Path 对象的转换

 2014/3/24 18:56:16  cucaracha  程序员俱乐部  我要评论(0)
  • 摘要:本文中,你将可以看到如何将Path对象转换为其它对象。本文所有例子都是基于下面的Path对象:Pathpath=Paths.get("/rafaelnadal/tournaments/2009","BNP.txt");将Path转换为String可以直接使用Path.toString()方法进行转换://output:\rafaelnadal\tournaments\2009\BNP.txtStringpath_to_string=path.toString();System.out
  • 标签:
本文中,你将可以看到如何将 Path 对象转换为其它对象。本文所有例子都是基于下面的 Path 对象:

class="java" name="code">Path path = Paths.get("/rafaelnadal/tournaments/2009", "BNP.txt");


将 Path 转换为 String

可以直接使用 Path.toString() 方法进行转换:
//output: \rafaelnadal\tournaments\2009\BNP.txt 
String path_to_string = path.toString(); 
System.out.println("Path to String: " + path_to_string); 


将 Path 转换为 URI

可以调用 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); 


将相对路径转换为绝对路径

从相对路径得到绝对路径是一个经常遇到的问题。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()); 


将 Path 转换为真实路径

调用 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); 
} 


将 Path 转换为 File


可以调用 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()); 


文章来源:http://www.aptusource.org/2014/03/nio-2-convert-path-object/
  • 相关文章
发表评论
用户名: 匿名