java中的Path和Files之Path

本文深入探讨了Java中Path和Files的使用方法,包括如何通过Paths.get方法创建Path对象,从配置文件中获取Path,以及Path类的各种常用方法,如resolve、relativize和normalize等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Path是一个目录名序列,后面可以跟一个文件名。路径中的第一个参数可以是根部件,如:/ 或者C:\ , 而允许访问的根部件取决于文件系统。以根部件开始的路径是绝对路径,反之则是相对路径。

获得 Path对象

1.通过 Paths.get 直接传入 String 字符串方法获得

例如:

public class Test {
	public static void main(String[] args) {
		Path absolutePath = Paths.get("/test1","test2");
		Path relativePath = Paths.get("test1", "test2","test3","test.txt");
		System.out.println("absolutePath: " + absolutePath);
		System.out.println("relativePath: " + relativePath);
	}
}

控制台输出:

absolutePath: /test1/test2
relativePath: test1/test2/test3/test.txt

静态的 Paths.get 方法接收一个或者多个字符串,并将他们用默认文件系统的路径分隔符(类 Unix 文件系统是 / ,Windows 系统是 \ )连接起来,然后解析连接起来的结果,如果表示的不是给定系统中的合法路径,就会抛出 InvalidPathException 异常,这个连接起来的结果就是一个 Path 对象(结果仅仅表示一个路径,该文件或者该文件夹并不一定真实存在)。

2.通过读取配置文件获得

  1. test.properties
test.dir=test
  1. 代码demo
public class Test {
	public static void main(String[] args) throws FileNotFoundException, IOException {
		Path relativePath = Paths.get(System.getProperty("user.dir"),"src","test.properties");
		Properties properties = new Properties();
		properties.load(new FileReader(relativePath.toFile()));
		String dir = properties.getProperty("test.dir");
		Path path = Paths.get(dir);
		System.out.println("path: " + path);
	}
}
  1. 控制台输出:
path: test

Path 常用方法

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

通过连接给定的字符串创建一个路径

public class Test {
	public static void main(String[] args) {
		/*
		 * static Path get(String first, String... more)
		 * 通过连接给定的字符串创建一个路径
		 */
		Path absolutePath = Paths.get("/test1","test2");
		Path relativePath = Paths.get("root","test1", "test2","test3","test.txt");
		System.out.println("absolutePath: " + absolutePath);
		System.out.println("relativePath: " + relativePath);
	}
}

控制台输出:

absolutePath: /test1/test2
relativePath: root/test1/test2/test3/test.txt
  1. Path resolve(Path other)
    Path resolve(String other)

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

public class Test {
	public static void main(String[] args) {
		Path absolutePath = Paths.get("/test1","test2");
		Path relativePath = Paths.get("root","test1", "test2","test3","test.txt");
		/*
		 * Path resolve(Path other)
		 * Path resolve(String other)
		 * 若 other 是绝对路径,那么就返回 other ;否则,返回通过连接 this 和 other 获得的
		 * 路径。
		 */
		Path p1 = absolutePath.resolve(relativePath);
		// other 是相对路径,返回absolutePath + relativePath
		System.out.println("resolve: " + p1);
		Path p2 = absolutePath.resolve(absolutePath);
		// other 是绝对路径直接返回 absolutePath
		System.out.println("resolve :" + p2);
	}
}

控制台输出:

resolve: /test1/test2/root/test1/test2/test3/test.txt
resolve :/test1/test2
  1. Path resolveSibling(Path other)
    Path resolveSibling(String other)

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

public class Test {
	public static void main(String[] args) {
		Path absolutePath = Paths.get("/test1","test2");
		Path relativePath = Paths.get("root","test1", "test2","test3","test.txt");
		/*
		 * Path resolveSibling(Path other)
		 * Path resolveSibling(String other)
		 * 若 other 是绝对路径, 那么就返回 other ;否则,返回通过连接 this 的
		 * 父路径和 other 获得的路径
		 */
		Path p3 = absolutePath.resolveSibling(absolutePath);
		// other 是绝对路径,返回 absolutePath
		System.out.println("resolveSibling: " +p3);
		// other 是相对路径, 返回 relativePath 的父路径 和 relativePath
		Path p4 = absolutePath.resolveSibling(relativePath);
		System.out.println("resolveSibling: " + p4);
	}
}

控制台输出:

resolveSibling: /test1/test2
resolveSibling: /test1/root/test1/test2/test3/test.txt
  1. Path relativize(Path other)

返回用 this 进行解析,相对于 other 的相对路径.

public class Test {
	public static void main(String[] args) {
		Path absolutePath = Paths.get("/test1","test2");
		Path relativePath = Paths.get("root","test1", "test2","test3","test.txt");
		/*
		 * Path relativize(Path other)
		 * 返回用 this 进行解析,相对于 other 的相对路径
		 */
		Path relativePath2 = Paths.get("root","test1", "test2","test4","test2.txt");
		Path p5 = relativePath.relativize(relativePath2);
		System.out.println("relativize: " +p5);
	}
}

控制台输出:

relativize: ../../test4/test2.txt
  1. Path normalize()

移除如 . 或者 … 等冗余的路径元素

public class Test {
	public static void main(String[] args) {
		/*
		 * Path normalize()
		 * 移除如 . 或者 .. 等冗余的路径元素
		 */
		Path p6 = Paths.get("test",".","test","..","test.txt");
		Path p7 = p6.normalize();
		System.out.println("normalize: " + p7);
	}
}

控制台输出:

normalize: test/test.txt
  1. Path toAbsolutePath()

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

public class Test {
	public static void main(String[] args) {
		Path relativePath = Paths.get("root","test1", "test2","test3","test.txt");
		/*
		 * Path toAbsolutePath()
		 * 返回与该路径等价的绝对路径
		 */
		Path p8 = relativePath.toAbsolutePath();
		System.out.println("toAbsolutePath: " + p8);
	}
}

控制台输出:

toAbsolutePath: /Users/zhangzheng/eclipse-workspace/test/root/test1/test2/test3/test.txt
  1. Path getParent()

返回父路径,或者没有父路径时返回null

public class Test {
	public static void main(String[] args) {
		Path absolutePath = Paths.get("/test1","test2");
		/*
		 * Path getParent()
		 * 返回父路径,或者没有父路径时返回null
		 */
		Path p9 = absolutePath.getParent();
		System.out.println("getParent: " + p9);
	}
}

控制台输出:

getParent: /test1
  1. Path getFileName();

返回该路径的最后一个部件,或者在该路径没有任何部件时返回,返回null

public class Test {
	public static void main(String[] args) {
		Path relativePath = Paths.get("root","test1", "test2","test3","test.txt");
		/*
		 * Path getFileName();
		 * 返回该路径的最后一个部件,或者在该路径没有任何部件时返回,返回null
		 */
		Path p10 = relativePath.getFileName();
		System.out.println("getFileName: " + p10);
	}
}

控制台输出:

getFileName: test.txt
  1. Path getRoot()

返回该路径的根

public class Test {
	public static void main(String[] args) {
		Path absolutePath = Paths.get("/test1","test2");
		/*
		 * Path getRoot()
		 * 返回该路径的根
		 */
		Path p11 = absolutePath.getRoot();
		System.out.println("getRoot: " + p11);
	}
}

控制台输出:

getRoot: /
  1. FIle toFile()

获得一个file 对象

public class Test {
	public static void main(String[] args) {
		Path relativePath = Paths.get("root","test1", "test2","test3","test.txt");
		/*
		 * FIle toFile()
		 * 获得一个file 对象
		 */
		File file = relativePath.toFile();
		System.out.println("toFile: " + file);
	}
}

控制台输出:

toFile: root/test1/test2/test3/test.txt
### Java 中 `Path` 类的 `listFiles` 方法使用 需要注意的是,在标准 Java 库中,`Path` 接口并没有直接提供名为 `listFiles` 的方法。通常情况下,列举目录中的文件会通过其他方式实现。 #### 使用 `DirectoryStream` 一种常见的方式是利用 `DirectoryStream< Path>` 来遍历指定路径下的条目: ```java import java.nio.file.*; import java.io.IOException; public class ListFilesExample { public static void main(String[] args) throws IOException { Path dir = Paths.get("D:\\webworkspace"); try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir)){ for(Path entry : stream){ System.out.println(entry.getFileName()); } } // 或者使用过滤器来只获取特定类型的文件 try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.java")){ for(Path entry : stream){ System.out.println(entry.getFileName()); } } } } ``` 此代码片段展示了如何创建一个 `DirectoryStream` 对象并迭代其中的内容[^1]。第二个例子还显示了可以传递模式给 `newDirectoryStream()` 函数以筛选出符合条件的文件[^2]。 #### 使用流式 API (`Stream<Path>`) 另一种现代的方法是采用更简洁的流处理风格来进行同样的操作: ```java import java.nio.file.*; import java.io.IOException; import java.util.Iterator; public class StreamListFilesExample { public static void main(String[] args) throws IOException { try (Stream<Path> stream = Files.list(Paths.get("C:/"))) { Iterator<Path> iterator = stream.iterator(); while(iterator.hasNext()){ Path file = iterator.next(); System.out.println(file.getFileName()); } } catch (IOException e) { e.printStackTrace(); } } } ``` 这段程序同样实现了列出 C:\ 下所有文件的功能,并且采用了更加函数式的编程范式。 对于想要访问具体位置上的单个文件的情况,则可以直接调用 `FileSystems.getDefault().getPath()` 方法构建目标路径对象[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值