How to get the current working directory in Java?

前端 未结 22 3118
时光说笑
时光说笑 2020-11-21 07:16

I want to access my current working directory using java.

My code :

 String current = new java.io.File( \".\" ).getCanonicalPath();
        System.ou         


        
22条回答
  •  长发绾君心
    2020-11-21 08:11

    On Linux when you run a jar file from terminal, these both will return the same String: "/home/CurrentUser", no matter, where youre jar file is. It depends just on what current directory are you using with your terminal, when you start the jar file.

    Paths.get("").toAbsolutePath().toString();
    
    System.getProperty("user.dir");
    

    If your Class with main would be called MainClass, then try:

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

    This will return a String with absolute path of the jar file.

提交回复
热议问题