java 中通过 java.nio.file.paths 类的静态方法 get() 来创建路径,该方法接收字符串参数并返回 path 接口的实现实例。调用时只需传入表示文件系统的字符串即可获取路径对象,若字符串格式非法会抛出 invalidpathexception。

Paths.get() 如何处理相对路径与绝对路径
Paths.get() 会根据传入字符串是否以根目录标识符开头自动区分相对路径和绝对路径,无需额外配置。在 Windows 系统中以盘符如 C: 开头被视为绝对路径,而在 Linux/Unix 系统中以 / 开头被视为绝对路径,其他情况均为相对路径。

使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathDemo {
public static void main(String[] args) {
// 创建相对路径
Path relativePath = Paths.get("docs", "report.txt");
System.out.println("Relative: " + relativePath);
// 创建绝对路径 (Windows示例)
Path absolutePathWin = Paths.get("C:\Users\admin\file.txt");
System.out.println("Absolute Win: " + absolutePathWin);
// 创建绝对路径 (Linux示例)
Path absolutePathLin = Paths.get("/var/log/syslog");
System.out.println("Absolute Lin: " + absolutePathLin);
}
}Paths.get() 遇到空值或非法字符时会发生什么
当传入 null 值时,Paths.get() 会直接抛出 NullPointerException;若字符串包含当前文件系统不支持的字符(如在 Windows 上使用 、<code>>、: 等),则会抛出 InvalidPathException。这些异常都是运行时异常,必须在代码中显式处理或声明抛出。
立即学习“Java免费学习笔记(深入)”;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.InvalidPathException;
public class PathErrorDemo {
public static void main(String[] args) {
try {
// 测试非法字符
Path badPath = Paths.get("file<name>.txt");
} catch (InvalidPathException e) {
System.out.println("Caught InvalidPathException: " + e.getMessage());
}
try {
// 测试 null 输入
Path nullPath = Paths.get(null);
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException");
}
}
}

















