标签:
package chapter1; import java.io.File; import java.io.IOException; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; /** * 定义Path 对象 * * @author longlong * * @mail borrip0419@gmail.com * */ public class PathTest { public static void main(String[] args) { /** * 1.定义一个绝对路径 */ Path path = Paths.get("c:/my/test1.log"); System.out.println(path); //get方法可以将参数 path = Paths.get("c:", "my" , "test1.log") ; System.out.println(path); /** * 2.定义一个相对路径 */ path = Paths.get("/my" , "test1.log") ; System.out.println(path); /** * 3.相对于工作目录路径 */ path = Paths.get("my" , "test1.log") ; System.out.println(path); /** * 4.路径的简写 : .表示当前目录 ..表示上级目录 */ path = Paths.get("c:/my/./test1.log").normalize() ; System.out.println(path); path = Paths.get("c:/my/./../test1.log").normalize() ; System.out.println(path); /** * 5. 定义 Path 同样可以使用 FileSystems.getDefault().getPath(...) */ /** * 6.取得Home路径 */ path = Paths.get(System.getProperty("user.home"), "downloads", "game.exe"); System.out.println(path); /** * 7.得到Path对象之后,获取其更多信息内容 */ path = Paths.get("c:/my/test1.log"); //a.获取其文件名称 System.out.println(path.getFileName()); //b.获取文件的根目录 System.out.println(path.getRoot()); //c.获取文件的上级目录路径 System.out.println(path.getParent()); //d.获取文件其路径上所有名称 for (int i = 0; i < path.getNameCount() ; i++) { System.out.println("Name element " + i + " is: " + path.getName(i)) ; } //e.获得子路径 System.out.println("Subpath (0,1): " + path.subpath(0, 1)); /** * 8.获得文件路径的URI 用于浏览器可以访问 */ System.out.println(path.toUri()); /** * 9.将相对路径转换为绝对路径 */ path = Paths.get("c:" , "my" ,"test" , "1.log") ; System.out.println(path.toAbsolutePath()); try { path.toRealPath(LinkOption.NOFOLLOW_LINKS); System.out.println(path); } catch (IOException e) { e.printStackTrace(); } /** * 10.将path转换为File */ File file = path.toFile() ; System.out.println(file); /** * 11.比较两个路径 */ Path path01 = Paths.get("BNP.txt"); Path path02 = Paths.get("AEGON.txt"); Path path02_to_path01 = path02.relativize(path01); System.out.println(path02_to_path01); } }
标签:
原文地址:http://my.oschina.net/long0419/blog/364736