0

I know we can use System.getProperty("os.name"); to get the os name. But due to some reason someone has set an environment variable called JAVA_TOOL_OPTIONS="-Dos.name=Windows 7" which is causing not to get the original OS name instead its always getting the OS name as Window 7.

Do we have any way where we can get the original OS details?

Nagaraju Chitimilla
  • 530
  • 3
  • 7
  • 23
  • Does this answer your question? [How do I programmatically determine operating system in Java?](https://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java) – Lindstorm Apr 06 '20 at 06:10
  • Unfortunately no. My question here is System.getProperty is not behaving correctly due the environment variable JAVA_TOOL_OPTIONS. – Nagaraju Chitimilla Apr 06 '20 at 06:18
  • If this actually is Windows and 'someone' is only faking the version not the platform, `os.version` is the MS internal version which _mostly_ (but not completely) maps to the `os.name` values. – dave_thompson_085 Apr 08 '20 at 07:58

1 Answers1

1

You can use Apache Commons Lang, class name is SystemUtils. You can use the below code.

String osName = SystemUtils.OS_NAME;
System.out.println("OS NAME: " + osName);

You have to add the Apache Commons Lang in the classpath.

If nothing works then you have to execute the commands specific to OS one by one until you get the correct result. But this is not the correct approach, it is just a work around.

For Windows, execute ver

For Linux, execute cat /etc/*-release or lsb_release -a

PythonLearner
  • 1,416
  • 7
  • 22
  • I just saw the implementation of SystemUtils. Here also we are using System.getProperty. `private static String getSystemProperty(final String property) { try { return System.getProperty(property); } catch (final SecurityException ex) { // we are not allowed to look at this property System.err.println("Caught a SecurityException reading the system property '" + property + "'; the SystemUtils property value will default to null."); return null; } }` – Nagaraju Chitimilla Apr 06 '20 at 06:14
  • Thanks but my question here is System.getProperty is not behaving correctly due the environment variable JAVA_TOOL_OPTIONS. – Nagaraju Chitimilla Apr 06 '20 at 07:08
  • If possible, can you remove `JAVA_TOOL_OPTIONS="-Dos.name=Windows 7"` from environment variable and check system property in java just to pin point the issue ? – PythonLearner Apr 06 '20 at 07:15
  • yes.. if i remove then this works..but unfortunately we can't remove this variable as some other software requires this entry. – Nagaraju Chitimilla Apr 06 '20 at 07:23
  • 2
    @NagarajuChitimilla Then remove that property from the global environment, and only set it for the specific program that does require it. – Mark Rotteveel Apr 06 '20 at 12:00