简体   繁体   中英

Why does System.getProperty("user.dir") not returning the expected value

When I tried the below code, it is not returning the current directory. Instead it is returning only . ie a dot .

String current = System.getProperty("user.dir");
System.out.println("Current working directory in Java : " + current);

Output:

Current working directory in Java :.

Whereever the value is coming from seems to be platform-specific but certainly . ie "dot" is not a particularly useful result. Not sure how it was processed but if your main aim is to get a meaningful value, you can use either of the following options as per this documentation :

  • getCanonicalPath()
  • getCanonicalFile()
  • getAbsolutePath()
  • getAbsoluteFile()

A Windows OS based example:

  • Ideal scenario:

    • Code Block:

       System.out.println("user.dir: "+System.getProperty("user.dir"));
    • Console Output:

       user.dir: C:\\Users\\AtechM_03\\LearnAutmation\\learn-automation
  • Alternative:

    • Code Block:

       String user_dir = System.getProperty("user.dir"); File pwdDir = new File(user_dir); System.out.println("Current working directory in Java : " + pwdDir.getCanonicalPath()); System.out.println("Current working directory in Java : " + pwdDir.getCanonicalFile()); System.out.println("Current working directory in Java : " + pwdDir.getAbsolutePath()); System.out.println("Current working directory in Java : " + pwdDir.getAbsoluteFile());
    • Console Output:

       Current working directory in Java : C:\\Users\\AtechM_03\\LearnAutmation\\learn-automation Current working directory in Java : C:\\Users\\AtechM_03\\LearnAutmation\\learn-automation Current working directory in Java : C:\\Users\\AtechM_03\\LearnAutmation\\learn-automation Current working directory in Java : C:\\Users\\AtechM_03\\LearnAutmation\\learn-automation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM