java 工作目录_Java程序获取当前工作目录

Java程序获取当前工作目录

在该程序中,您将学习获取Java中的当前工作目录。

示例1:获取当前工作目录

public class CurrDirectory {

public static void main(String[] args) {

String path = System.getProperty("user.dir");

System.out.println("Working Directory = " + path);

}

}

运行该程序时,输出为:Working Directory = C:\Users\Admin\Desktop\currDir

在上面的程序中,我们使用System的getProperty()方法来获取user.dir程序的属性。这将返回包含我们的Java项目的目录。

示例2:使用路径获取当前工作目录

import java.nio.file.Paths;

public class CurrDirectory {

public static void main(String[] args) {

String path = Paths.get("").toAbsolutePath().toString();

System.out.println("Working Directory = " + path);

}

}

运行该程序时,输出为:Working Directory = C:\Users\Admin\Desktop\currDir

在上述程序中,我们使用Path的get()方法来获取程序的当前路径。这将返回到工作目录的相对路径。

然后,我们使用toAbsolutePath()将相对路径更改为绝对路径。 由于它返回一个Path对象,因此我们需要使用toString()方法将其更改为字符串

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值