-1

I cant figure out why System.getProperty("home.dir") is returning null instead of the current working directory.

I am using Eclipse Mars2.0 IDE on Ubuntu 16.04. I guess, this hardly matters which IDE I am using or the OS version.

package test;

public class testing {
    public static void main (String args[])
    {
        System.out.println(System.getProperty("home.dir"));
    }

}

I am expecting to get a return for this code as something like /home/[user]/Workspace/test

Mickael
  • 3,506
  • 1
  • 21
  • 33
Avirup Das
  • 189
  • 1
  • 3
  • 15
  • How to remove the blue box with that text above: "This question already has answers here:" the answer is wrong, the user home directory is a different concept than a working directory. – Angel O'Sphere Dec 18 '19 at 14:00

1 Answers1

2

Home.dir is not a java property as specified here:

https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

If by working directory you mean the users working directory then user.home should work.

Example:

    System.out.println(System.getProperty("user.home"));

Outputted:

C:\Users\User

If you mean the .jars working directory then I do not believe such a property exists. Instead use:

    your_class.class.getProtectionDomain().getCodeSource().getLocation().getPath(); 

This will return a string specifying where the jar is situated currently.

Example:

    System.out.println(new File(**TestLighting.class.getProtectionDomain().getCodeSource().getLocation().getPath()**));

(new File() is to get the correct formatting, it was /C:/...)

Outputted:

C:\Users\User\Documents\Java\Netbeans\Engine\build\test\classes

(This is the path of where the jar is being run from)

If home.dir is a system environment variable then you would use System.getenv()

  • I actually need the absolute path of the initialized application – Avirup Das Sep 04 '16 at 06:46
  • As in where the jar you run is located? If so then then that is what I meant by **.jars working directory**. If not then please clarify with an example – Jonathan Botha Sep 04 '16 at 07:22
  • Thank you, I also added an example, I believe my second suggestion with 'your_class.class.getProtectionDomain().getCodeSource().getLocation().getPath();' is the correct one that you are looking for. – Jonathan Botha Sep 04 '16 at 10:37
  • Yes, this workaround worked. Thank you.However, I cant find out why System.getProperty("home.dir") did not work on the first place. – Avirup Das Sep 04 '16 at 11:32
  • Home.dir is not a system property. Look at the link I put there. It shows all system properties. – Jonathan Botha Sep 04 '16 at 12:13
  • Ahh.. Thats it... I require that "user.dir" System property to work on. Had it confused with "user.home". - Thank you so much... – Avirup Das Sep 04 '16 at 12:36