How to get the current working directory in Java?

前端 未结 22 3155
时光说笑
时光说笑 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());
        }
    }
    

提交回复
热议问题