How to get the current working directory in Java?

前端 未结 22 3075
时光说笑
时光说笑 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:15

    Use CodeSource#getLocation().

    This works fine in JAR files as well. You can obtain CodeSource by ProtectionDomain#getCodeSource() and the ProtectionDomain in turn can be obtained by Class#getProtectionDomain().

    public class Test {
        public static void main(String... args) throws Exception {
            URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
            System.out.println(location.getFile());
        }
    }
    
    0 讨论(0)
  • 2020-11-21 08:15

    generally, as a File object:

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

    you may want to have full qualified string like "D:/a/b/c" doing:

    getCwd().getAbsolutePath()
    
    0 讨论(0)
  • 2020-11-21 08:15

    Mention that it is checked only in Windows but i think it works perfect on other Operating Systems [Linux,MacOs,Solaris] :).


    I had 2 .jar files in the same directory . I wanted from the one .jar file to start the other .jar file which is in the same directory.

    The problem is that when you start it from the cmd the current directory is system32.


    Warnings!

    • The below seems to work pretty well in all the test i have done even with folder name ;][[;'57f2g34g87-8+9-09!2#@!$%^^&() or ()%&$%^@# it works well.
    • I am using the ProcessBuilder with the below as following:

    0 讨论(0)
  • 2020-11-21 08:17

    I hope you want to access the current directory including the package i.e. If your Java program is in c:\myApp\com\foo\src\service\MyTest.java and you want to print until c:\myApp\com\foo\src\service then you can try the following code:

    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);
    

    Note: This code is only tested in Windows with Oracle JRE.

    0 讨论(0)
提交回复
热议问题