java获取文件的绝对路径_什么是Java NIO Path接口操作文件,如何操作使用?

1、前言

Path接口位于java.nio.file包中,所以Path接口的完全限定名称为java.nio.file.Path。Java Path实例表示文件系统中的路径。一个路径可以指向一个文件或一个目录。路径可以是绝对路径,也可以是相对路径。在许多方面,java.nio.file.Path接口类似于java.io.File类,但是有一些细微的差别。不过,在许多情况下,您可以使用Path接口来替换File类的使用。

2、Path 的使用

2.1 创建一个Path实例

可以使用Paths类(java.nio.file.Paths)中的静态方法来创建路径实例,名为Paths.get()。

public class PathExample {    public static void main(String[] args) {        Path path = Paths.get("D:dataestlog");    }}12345

2.2 API的使用

  1. static Path get(String first, String… more)

将给定的字符串拼接成路径

 Path absolutePath = Paths.get("G:","data","est","log");        Path relativepath = Paths.get("test","log");        System.out.println("绝对路径是:"+absolutePath);        System.out.println("相对路径是:"+relativepath);1234

控制台输出

绝对路径是:G:dataestlog相对路径是:testlog12
  1. Path resolve(Path other) 或 Path resolve(String other)

根据指定路径解析路径 若 other 是绝对路径,那么就返回 other ;否则,返回通过连接 this 和 other 获得的路径。

Path path1 = Paths.get("D:dataestlog"); System.out.println(path1.resolve("/log")); //D:log System.out.println(path1.resolve("./log"));   //D:dataestlog.log System.out.println(path1.resolve("../log"));   //D:dataestlog..log1234567
  1. Path resolveSibling(Path other) 或 Path resolveSibling(String other)

若 other 是绝对路径, 那么就返回 other ;否则,返回通过连接 this 的父路径和 other 获得的路径

 Path path1 = Paths.get("D:dataestlog");        System.out.println(path1.resolveSibling("/log")); //D:log               System.out.println(path1.resolveSibling("./log"));  //D:dataest.log               System.out.println(path1.resolveSibling("../log"));  //D:dataest..log1234567
  1. toAbsolutePath()

返回与该路径等价的绝对路径

System.out.println(Paths.get("log","test").toAbsolutePath()); //G:IDEAplacemultithreadinglogest12
  1. relativize(Path other)

构造此路径和给定路径之间的相对路径。

Path path2 = Paths.get("D:dataestlogsjava.log");        System.out.println(path1.relativize(path2)); //  ..logsjava.log123
  1. subpath(int beginIndex, int endIndex)

截取路径,包括第一个索引,不包括第二个索引

Path path = Paths.get("D:dataestlog");System.out.println(path.subpath(0, 2));  //   dataest
62dcda43a61734d1bec735e07872892e.gif
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值