java如何获取路径
获取当前工作目录路径
使用 System.getProperty("user.dir") 可以直接获取当前 Java 程序运行的绝对路径。
String currentDir = System.getProperty("user.dir");
System.out.println("当前工作目录: " + currentDir);
获取类路径下的资源路径
通过 ClassLoader.getResource() 或 Class.getResource() 可以获取类路径(Classpath)下的资源路径,适用于读取配置文件等场景。

// 使用 ClassLoader
String resourcePath = getClass().getClassLoader().getResource("config.properties").getPath();
System.out.println("资源路径: " + resourcePath);
// 使用 Class(相对路径)
String relativePath = getClass().getResource("/data/file.txt").getPath();
System.out.println("相对资源路径: " + relativePath);
获取文件绝对路径
通过 File 对象的 getAbsolutePath() 方法可以获取文件的绝对路径。
File file = new File("example.txt");
String absolutePath = file.getAbsolutePath();
System.out.println("文件绝对路径: " + absolutePath);
获取临时目录路径
使用 System.getProperty("java.io.tmpdir") 可以获取系统的临时目录路径。

String tempDir = System.getProperty("java.io.tmpdir");
System.out.println("临时目录: " + tempDir);
获取用户主目录路径
通过 System.getProperty("user.home") 可以获取用户的主目录路径。
String homeDir = System.getProperty("user.home");
System.out.println("用户主目录: " + homeDir);
注意事项
- 路径分隔符在不同操作系统中可能不同(Windows 用
\,Linux/macOS 用/),建议使用File.separator或Paths.get()(Java 7+)处理跨平台兼容性。 - 使用
Paths.get()和Path.toAbsolutePath()可以更安全地处理路径操作(需 Java 7 及以上版本)。import java.nio.file.Paths; import java.nio.file.Path;
Path path = Paths.get("example.txt"); System.out.println("NIO 路径: " + path.toAbsolutePath());






