How to get the current working directory in Java?

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

提交回复
热议问题