我想使用Java访问我的当前工作目录。

我的代码:

 String currentPath = new java.io.File(".").getCanonicalPath();
 System.out.println("Current dir:" + currentPath);

 String currentDir = System.getProperty("user.dir");
 System.out.println("Current dir using System:" + currentDir);

输出:

Current dir: C:\WINDOWS\system32
Current dir using System: C:\WINDOWS\system32

我的输出不正确,因为C驱动器不是我的当前目录。

如何获取当前目录?


当前回答

你可以使用new File("./")。这样isDirectory()返回true(至少在Windows平台上)。另一方面,new File("") isDirectory()返回false。

其他回答

我最喜欢的方法是从附加到当前运行进程的系统环境变量中获取。在这种情况下,您的应用程序由JVM管理。

String currentDir = System.getenv("PWD");
/*
 /home/$User/Documents/java
*/

查看其他你可能会发现有用的环境变量,如home dir, os版本........

//Home directory
String HomeDir = System.getEnv("HOME");


//Outputs for unix
/home/$USER

//Device user
String user = System.getEnv("USERNAME");


//Outputs for unix
$USER

这种方法的美妙之处在于,对于所有类型的操作系统平台,所有路径都将被解析

你可以使用new File("./")。这样isDirectory()返回true(至少在Windows平台上)。另一方面,new File("") isDirectory()返回false。

这就是我的解决方案

File currentDir = new File("");

这将给你当前工作目录的路径:

Path path = FileSystems.getDefault().getPath(".");

这将为您提供工作目录中名为“Foo.txt”的文件的路径:

Path path = FileSystems.getDefault().getPath("Foo.txt");

编辑: 获取当前目录的绝对路径。

Path path = FileSystems.getDefault().getPath(".").toAbsolutePath();

*更新* 获取当前工作目录:

Path path = FileSystems.getDefault().getPath("").toAbsolutePath();

我希望你想访问当前目录,包括包,即,如果你的Java程序在c:\myApp\com\foo\src\service\MyTest.java,你想打印直到c:\myApp\com\foo\src\service,那么你可以尝试以下代码:

String myCurrentDir = System.getProperty("user.dir")
            + File.separator
            + System.getProperty("sun.java.command")
                    .substring(0, System.getProperty("sun.java.command").lastIndexOf("."))
                    .replace(".", File.separator);
    System.out.println(myCurrentDir);

注意:此代码仅在Windows和Oracle JRE中测试。