How to get the current working directory in Java?

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

    None of the answers posted here worked for me. Here is what did work:

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

    Edit: The final version in my code:

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

提交回复
热议问题