java Paths 的各个方法的使用 demo
时间: 2024-05-15 09:14:33 浏览: 16
`java.nio.file.Paths` 是 Java 中用于操作文件路径的工具类,提供了一些方便的方法来创建、操作和获取文件路径信息。下面是 `Paths` 类的几个常用方法及其使用示例:
1. `Paths.get(String first, String... more)`:根据给定的路径字符串创建一个 `Path` 对象。
```java
Path path1 = Paths.get("C:", "Users", "username", "Desktop", "file.txt");
Path path2 = Paths.get("/usr/local/bin");
```
2. `Path resolve(String other)`:将当前路径与给定路径组合起来,返回一个新的 `Path` 对象。
```java
Path path1 = Paths.get("/usr/local/bin");
Path path2 = path1.resolve("java");
```
3. `Path normalize()`:返回一个规范化的路径,即去除冗余的斜杠、点号和双点号等。
```java
Path path1 = Paths.get("/usr/local/./bin/../lib/");
Path path2 = path1.normalize();
```
4. `Path toAbsolutePath()`:返回一个绝对路径,即包含完整的路径信息。
```java
Path path1 = Paths.get("file.txt");
Path path2 = path1.toAbsolutePath();
```
5. `Path getFileName()`:返回路径中的文件名。
```java
Path path = Paths.get("/usr/local/bin/java");
Path fileName = path.getFileName(); // 返回 "java"
```
6. `Path getParent()`:返回路径中的父目录。
```java
Path path = Paths.get("/usr/local/bin/java");
Path parent = path.getParent(); // 返回 "/usr/local/bin"
```
7. `Path subpath(int beginIndex, int endIndex)`:返回路径中从 `beginIndex` 到 `endIndex` 之间的子路径。
```java
Path path = Paths.get("/usr/local/bin/java");
Path subpath = path.subpath(1, 3); // 返回 "local/bin"
```
8. `Path relativize(Path other)`:返回当前路径相对于给定路径的相对路径。
```java
Path path1 = Paths.get("/usr/local/bin");
Path path2 = Paths.get("/usr/local/share");
Path relativePath = path1.relativize(path2); // 返回 "../share"
```
以上是 `Paths` 类的一些常用方法及其使用示例,更多详细的方法及其参数说明可以参考官方文档。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)