使用Java获取当前工作目录

时间:2011-02-02 05:24:07

标签: java working-directory

我想使用

访问我当前的工作目录
 String current = new java.io.File( "." ).getCanonicalPath();
        System.out.println("Current dir:"+current);
 String currentDir = System.getProperty("user.dir");
        System.out.println("Current dir using System:" +currentDir);

OutPut:

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

我的输出不正确,因为C盘不是我当前的目录。 在这方面需要帮助。

25 个答案:

答案 0 :(得分:1024)

public class JavaApplication1 {
  public static void main(String[] args) {
       System.out.println("Working Directory = " +
              System.getProperty("user.dir"));
  }
}

这将打印出应用程序初始化的完整绝对路径。

答案 1 :(得分:339)

请参阅:http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

使用java.nio.file.Pathjava.nio.file.Paths,您可以执行以下操作来显示Java认为您当前的路径。这适用于7及以上,并使用NIO。

Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);

这会输出Current relative path is: /Users/george/NetBeansProjects/Tutorials,在我的情况下是我运行类的地方。以相对方式构造路径,通过不使用前导分隔符来指示您正在构建绝对路径,将使用此相对路径作为起点。

答案 2 :(得分:210)

以下适用于Java 7及更高版本(有关文档,请参阅here)。

import java.nio.file.Paths;

Paths.get(".").toAbsolutePath().normalize().toString();

答案 3 :(得分:51)

这将为您提供当前工作目录的路径:

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

这将为您提供一个名为" Foo.txt"的文件的路径。在工作目录中:

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

修改: 要获取当前目录的绝对路径:

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

答案 4 :(得分:32)

这是我的解决方案

File currentDir = new File("");

答案 5 :(得分:30)

是什么让您认为 c:\ windows \ system32 不是您当前的目录? user.dir属性显式为“用户的当前工作目录”。

换句话说,除非您从命令行启动Java,否则 c:\ windows \ system32 可能是您的CWD。也就是说,如果您双击以启动程序,则CWD不太可能是您双击的目录。

编辑:似乎只适用于旧版Windows和/或Java版本。

答案 6 :(得分:25)

使用CodeSource#getLocation()

这也适用于JAR文件。您可以ProtectionDomain#getCodeSource()获取CodeSourceClass#getProtectionDomain()可以获得ProtectionDomain

public class Test {
    public static void main(String... args) throws Exception {
        URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
        System.out.println(location.getFile());
    }
}

答案 7 :(得分:23)

我在评论中找到了这种解决方案,该解决方案比其他解决方案更好,并且更便于移植:

String cwd = new File("").getAbsolutePath();

答案 8 :(得分:23)

this.getClass().getClassLoader().getResource("").getPath()

答案 9 :(得分:17)

通常,作为File对象:

File getCwd() {
  return new File("").getAbsoluteFile();
}

您可能希望拥有完整的限定字符串,例如“D:/ a / b / c”:

getCwd().getAbsolutePath()

答案 10 :(得分:12)

我在Linux上并且对这两种方法都得到了相同的结果:

@Test
public void aaa()
{
    System.err.println(Paths.get("").toAbsolutePath().toString());

    System.err.println(System.getProperty("user.dir"));
}

Paths.get("") docs

System.getProperty("user.dir") docs

答案 11 :(得分:5)

当前工作目录在不同的Java实现中的定义不同。对于Java 7之前的某个版本,没有一致的方法来获取工作目录。您可以通过使用-D启动Java文件并定义保存信息的变量来解决此问题

这样的东西
java -D com.mycompany.workingDir="%0"

这不太对,但你明白了。然后System.getProperty("com.mycompany.workingDir") ...

答案 12 :(得分:5)

使用Windows user.dir按预期返回目录,但是当您使用提升的权限(以管理员身份运行)启动应用程序时,则不会返回该目录,在这种情况下,您将获得C:\ WINDOWS \ system32

答案 13 :(得分:4)

终端运行 jar 文件时 Linux ,这两者将返回相同的String " / home / CurrentUser" ,无论你的jar文件在哪里。当你启动jar文件时,它只取决于你在终端上使用的当前目录。

Paths.get("").toAbsolutePath().toString();

System.getProperty("user.dir");

如果您的Class main被称为MainClass,请尝试:

MainClass.class.getProtectionDomain().getCodeSource().getLocation().getFile();

这将返回String jar 文件的绝对路径

答案 14 :(得分:3)

提到仅在Windows中进行检查,但我认为它在其他操作系统[Linux,MacOs,Solaris]上运行良好:)。

我在同一目录中有 2 .jar个文件。我希望从一个.jar文件中启动位于同一目录中的另一个.jar文件。

问题是,当您从cmd启动它时,当前目录为system32

  

警告!

  • 以下似乎在我做过的所有测试中都能很好地工作 文件夹名称为;][[;'57f2g34g87-8+9-09!2#@!$%^^&()()%&$%^@# 它运作良好。
  • 我正在使用ProcessBuilder以及以下内容:

...

//The class from which i called this was the class `Main`
String path = getBasePathForClass(Main.class);
String applicationPath=  new File(path + "application.jar").getAbsolutePath();


System.out.println("Directory Path is : "+applicationPath);

//Your know try catch here
//Mention that sometimes it doesn't work for example with folder `;][[;'57f2g34g87-8+9-09!2#@!$%^^&()` 
ProcessBuilder builder = new ProcessBuilder("java", "-jar", applicationPath);
builder.redirectErrorStream(true);
Process process = builder.start();

//...code

getBasePathForClass(Class<?> classs)

    /**
     * Returns the absolute path of the current directory in which the given
     * class
     * file is.
     * 
     * @param classs
     * @return The absolute path of the current directory in which the class
     *         file is.
     * @author GOXR3PLUS[StackOverFlow user] + bachden [StackOverFlow user]
     */
    public static final String getBasePathForClass(Class<?> classs) {

        // Local variables
        File file;
        String basePath = "";
        boolean failed = false;

        // Let's give a first try
        try {
            file = new File(classs.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());

            if (file.isFile() || file.getPath().endsWith(".jar") || file.getPath().endsWith(".zip")) {
                basePath = file.getParent();
            } else {
                basePath = file.getPath();
            }
        } catch (URISyntaxException ex) {
            failed = true;
            Logger.getLogger(classs.getName()).log(Level.WARNING,
                    "Cannot firgue out base path for class with way (1): ", ex);
        }

        // The above failed?
        if (failed) {
            try {
                file = new File(classs.getClassLoader().getResource("").toURI().getPath());
                basePath = file.getAbsolutePath();

                // the below is for testing purposes...
                // starts with File.separator?
                // String l = local.replaceFirst("[" + File.separator +
                // "/\\\\]", "")
            } catch (URISyntaxException ex) {
                Logger.getLogger(classs.getName()).log(Level.WARNING,
                        "Cannot firgue out base path for class with way (2): ", ex);
            }
        }

        // fix to run inside eclipse
        if (basePath.endsWith(File.separator + "lib") || basePath.endsWith(File.separator + "bin")
                || basePath.endsWith("bin" + File.separator) || basePath.endsWith("lib" + File.separator)) {
            basePath = basePath.substring(0, basePath.length() - 4);
        }
        // fix to run inside netbeans
        if (basePath.endsWith(File.separator + "build" + File.separator + "classes")) {
            basePath = basePath.substring(0, basePath.length() - 14);
        }
        // end fix
        if (!basePath.endsWith(File.separator)) {
            basePath = basePath + File.separator;
        }
        return basePath;
    }

答案 15 :(得分:3)

我希望您想要访问包含该软件包的当前目录,即如果您的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进行测试。

答案 16 :(得分:1)

假设您尝试在eclipse或netbean中运行项目,或者从命令行独立运行。我已经写了一个方法来解决它

public static final String getBasePathForClass(Class<?> clazz) {
    File file;
    try {
        String basePath = null;
        file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
        if (file.isFile() || file.getPath().endsWith(".jar") || file.getPath().endsWith(".zip")) {
            basePath = file.getParent();
        } else {
            basePath = file.getPath();
        }
        // fix to run inside eclipse
        if (basePath.endsWith(File.separator + "lib") || basePath.endsWith(File.separator + "bin")
                || basePath.endsWith("bin" + File.separator) || basePath.endsWith("lib" + File.separator)) {
            basePath = basePath.substring(0, basePath.length() - 4);
        }
        // fix to run inside netbean
        if (basePath.endsWith(File.separator + "build" + File.separator + "classes")) {
            basePath = basePath.substring(0, basePath.length() - 14);
        }
        // end fix
        if (!basePath.endsWith(File.separator)) {
            basePath = basePath + File.separator;
        }
        return basePath;
    } catch (URISyntaxException e) {
        throw new RuntimeException("Cannot firgue out base path for class: " + clazz.getName());
    }
}

要使用,无论您想要获取基本路径来读取文件,您都可以将锚类传递给上面的方法,结果可能是您需要的东西:D

最佳,

答案 17 :(得分:1)

当混乱时刻冒出来时,这是我的银子弹。(请首先将其称为主要内容)。例如,IDE可能会将JVM转换为其他版本。该静态函数搜索当前进程PID,并在该pid上打开VisualVM。混乱就在那里停止了,因为您想要全部并获得了...

  public static void callJVisualVM() {
    System.out.println("USER:DIR!:" + System.getProperty("user.dir"));
    //next search current jdk/jre
    String jre_root = null;
    String start = "vir";
    try {
        java.lang.management.RuntimeMXBean runtime =
                java.lang.management.ManagementFactory.getRuntimeMXBean();
        String jvmName = runtime.getName();
        System.out.println("JVM Name = " + jvmName);
        long pid = Long.valueOf(jvmName.split("@")[0]);
        System.out.println("JVM PID  = " + pid);
        Runtime thisRun = Runtime.getRuntime();
        jre_root = System.getProperty("java.home");
        System.out.println("jre_root:" + jre_root);
        start = jre_root.concat("\\..\\bin\\jvisualvm.exe " + "--openpid " + pid);
        thisRun.exec(start);
    } catch (Exception e) {
        System.getProperties().list(System.out);
        e.printStackTrace();
    }
}

答案 18 :(得分:0)

这里发布的答案都不适合我。这是做了什么工作:

java.nio.file.Paths.get(
  getClass().getProtectionDomain().getCodeSource().getLocation().toURI()
);

编辑:我的代码中的最终版本:

URL myURL = getClass().getProtectionDomain().getCodeSource().getLocation();
java.net.URI myURI = null;
try {
    myURI = myURL.toURI();
} catch (URISyntaxException e1) 
{}
return java.nio.file.Paths.get(myURI).toFile().toString()

答案 19 :(得分:0)

这并不是所要的,但这是一个重要的注意事项:在Windows计算机上运行Java时,Oracle安装程序将“ java.exe”放入C:\ Windows \ system32,这就是Java应用程序的启动器(除非PATH前面有一个java.exe,并且Java应用程序是从命令行运行的)。这就是File(“。”)始终返回C:\ Windows \ system32,的原因,原因是从macOS或* nix实现运行示例时,返回的结果与Windows不同。

不幸的是,就我在20年的Java编码中发现的情况而言,实际上并没有一个普遍正确的答案,除非您想使用JNI Invocation创建自己的本机启动程序可执行文件,并从本机获取当前工作目录启动器启动时的代码。其他所有东西至少都会在某些情况下可能会打破细微差别。

答案 20 :(得分:0)

尝试这样的事情我知道我的答案迟到了但是这个明显的事情发生在 java8 一个新版本中,从那里提出了这个问题但是..

代码

import java.io.File;

public class Find_this_dir {

    public static void main(String[] args) {

//some sort of a bug in java path is correct but file dose not exist
        File this_dir = new File("");

//but these both commands work too to get current dir        
//      File this_dir_2 = new File(this_dir.getAbsolutePath());
        File this_dir_2 = new File(new File("").getAbsolutePath());

        System.out.println("new File(" + "\"\"" + ")");
        System.out.println(this_dir.getAbsolutePath());
        System.out.println(this_dir.exists());
        System.out.println("");
        System.out.println("new File(" + "new File(" + "\"\"" + ").getAbsolutePath()" + ")");
        System.out.println(this_dir_2.getAbsolutePath());
        System.out.println(this_dir_2.exists());
    }
}

这将起作用并向您显示当前路径,但我现在不知道为什么除了我使用 Java8 之外 java 无法在 new File(""); 中找到当前目录编译器...

这很好用我什至测试过new File(new File("").getAbsolutePath());

现在您在 File 对象中有当前目录,所以(示例文件对象是 f),

f.getAbsolutePath() 会给你一个字符串变量类型的路径...

在不是 C 盘的另一个目录中测试工作正常

答案 21 :(得分:0)

对于 Java 11,您还可以使用:

var path = Path.of(".").toRealPath();

答案 22 :(得分:0)

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

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

查看其他可能有用的环境变量,例如 home dir、os version ........

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


//Outputs for unix
/home/$USER

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


//Outputs for unix
$USER

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

答案 23 :(得分:-6)

System.getProperty("java.class.path")

答案 24 :(得分:-6)

这是当前目录名称

String path="/home/prasad/Desktop/folderName";
File folder = new File(path);
String folderName=folder.getAbsoluteFile().getName();

这是当前目录路径

String path=folder.getPath();