<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>
很多朋友都想知道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:UsersAdminDesktopcurrDir
在上面的程序中,使用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:UsersAdminDesktopcurrDir
在上述程序中,使用Path的get()方法来获取程序的当前路径,这将返回到工作目录的相对路径。
然后使用toAbsolutePath()将相对路径更改为绝对路径。 由于它返回一个Path对象,因此需要使用toString()方法将其更改为字符串。