How to Programmatically Determine Operating System in Java

How do I programmatically determine operating system in Java?

You can use:

System.getProperty("os.name")

P.S. You may find this code useful:

class ShowProperties {
public static void main(String[] args) {
System.getProperties().list(System.out);
}
}

All it does is print out all the properties provided by your Java implementations. It'll give you an idea of what you can find out about your Java environment via properties. :-)

How Java determine operating system name?

Simply have a look into the OpenJDK source code.

  • Windows src/windows/native/java/lang/java_props_md.c

    line 353: GetVersionEx((OSVERSIONINFO *) &ver);

    more infos about GetVersionEx
  • Linux/Solaris/MacOS src/solaris/native/java/lang/java_props_md.c

    line 504: uname(&name);

    more infos about uname

How to determine 32-bit OS or 64-bit OS from Java application

You can run

System.getProperty("os.arch")

to retrieve the systems architecture. My Windows 64bit system will return amd64 as os.arch value.

How to find whether a process is running on Windows/Linux

I ended up creating a method that would return a Map<Integer, String> for all processes by running os-specific commands:

public Map<Integer, String> getProcesses() {
final Map<Integer, String> processes = Maps.newHashMap();
final boolean windows = System.getProperty("os.name").contains("Windows");
try {
final Process process = Runtime.getRuntime().exec(windows ? "tasklist /fo csv /nh" : "ps -e");
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
reader.lines().skip(1).forEach(x -> { // the first line is usually just a line to explain the format
if (windows) {
// "name","id","type","priority","memory?"
final String[] split = x.replace("\"", "").split(",");
processes.put(Integer.valueOf(split[1]), split[0]);
}
else {
// id tty time command
final String[] split = Arrays.stream(x.trim().split(" ")).map(String::trim)
.filter(s -> !s.isEmpty()).toArray(String[]::new); // yikes
processes.put(Integer.valueOf(split[0]), split[split.length - 1]);
}
});
}
}
catch (IOException e) {
e.printStackTrace();
}

return processes;
}

This hasn't been tested on Windows, but it should work. It also hasn't been tested on literally anything else other than Linux, but I hope this serves as a helpful method for others to work off of.



Related Topics



Leave a reply



Submit