实现说明
除了类 WorkingDirectory和函数 main,文件里再无其他定义。
使用要点
- 演示输出是带标签的(
user.dir =、empty path =、config path =),每个操作都会留下自己的一行标注。
常见问题
运行「当前工作目录解析」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 user.dir =、empty path =、config path = 标签标明各步骤。
核心语句
String fromProperty = System.getProperty("user.dir");
Path config = Path.of("config", "app.properties");
Path fromEmpty = Paths.get("").toAbsolutePath();
代码示例
import java.nio.file.Path;
import java.nio.file.Paths;
public class WorkingDirectory {
public static void main(String[] args) {
// user.dir 属性:JVM 启动时所在的 current working directory
String fromProperty = System.getProperty("user.dir");
// 空相对路径锚定到 user.dir:working directory 就是相对路径的解析基准
Path fromEmpty = Paths.get("").toAbsolutePath();
System.out.println("user.dir = " + fromProperty);
System.out.println("empty path = " + fromEmpty);
// 相对路径按同一基准解析,与进程从哪里被拉起无关
Path config = Path.of("config", "app.properties");
System.out.println("config path = " + config.toAbsolutePath().normalize());
}
}