Java中获取相对路径的方法有多种。以下是其中一种常见的方法:
System.getProperty("user.dir")
方法获取当前工作目录(即项目的根目录)的绝对路径。String currentPath = System.getProperty("user.dir");
String relativePath = "src/main/resources/file.txt";
String currentPath = System.getProperty("user.dir");
String absolutePath = currentPath + File.separator + relativePath;
File file = new File(absolutePath);
请注意,以上方法中的File.separator
是系统相关的文件分隔符(在Windows上是\
,在Linux上是/
)。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:Java怎么获取相对路径文件