zoukankan      html  css  js  c++  java
  • 十五、Java NIO Path

    所有文章

    https://www.cnblogs.com/lay2017/p/12901123.html

    正文

    Path是从Java 7开始加入NIO软件包的。它可以表示一个文件,也可以表示一个路径。可以是绝对路径,也可以是相对路径。

    你可能会觉得Path和常见的File很相似,大多数场景下File和Path可以相互替换,但是还是存在一些细微的不同点。以下是关于Path的一些用法

    创建Path

    public class PathExample {
    
        public static void main(String[] args) {
            Path path = Paths.get("c:\data\myfile.txt");
        }
    }

    Path的创建通过Paths的get方法

    创建绝对路径

    windows系统下

    Path path = Paths.get("c:\data\myfile.txt");

    unix系统下

    Path path = Paths.get("/home/jakobjenkov/myfile.txt");

    如果是windows系统下使用了

    /home/jakobjenkov/myfile.txt

    会被解释为

    C:/home/jakobjenkov/myfile.txt

    创建相对路径

    创建相对路径使用

    Paths.get(basePath, relativePath)

    示例代码

    Path projects = Paths.get("d:\data", "projects");
    
    Path file     = Paths.get("d:\data", "projects\a-project\myfile.txt");

    projects是:d:\data\projects

    file是:d:\data\projects\a-project\myfile.txt

    相对路径还有两个操作符辅助

    . :表示当前目录

    .. :表示上级目录

    路径中存在 . 符号,表示当前目录

    Path currentDir = Paths.get("d:\data\projects.a-project");

    路径

    d:dataprojectsa-project

    如果是 .. 符号,表示上级目录

    String path = "d:\data\projects\a-project\..\another-project";
    Path parentDir2 = Paths.get(path);

    路径

    d:dataprojectsanother-project

    同样的还可以这样写

    Path path1 = Paths.get("d:\data\projects", ".\a-project");
    
    Path path2 = Paths.get("d:\data\projects\a-project",
                           "..\another-project");

    Path.normalize()方法

    以下是normalize方法示例

    String originalPath = "d:\data\projects\a-project\..\another-project";
    
    Path path1 = Paths.get(originalPath);
    System.out.println("path1 = " + path1);
    
    Path path2 = path1.normalize();
    System.out.println("path2 = " + path2);

    打印结果

    path1 = d:dataprojectsa-project..another-project
    path2 = d:dataprojectsanother-project

    可以看到,normalize不包含如:.. 这样的符号

  • 相关阅读:
    vim 常用命令
    centos 安装mysql
    centos部署ftp
    centos 6.8部署nginx
    ndk学习16: unix domain socket
    ndk学习14: 进程
    ndk学习13: proc
    ndk学习11: linux内存管理
    ndk学习10: linux文件系统
    ndk学习9: 动态使用共享库
  • 原文地址:https://www.cnblogs.com/lay2017/p/12916968.html
Copyright © 2011-2022 走看看