Skip to content

Java OS Operations

Although Java's design philosophy is "Write Once, Run Anywhere," with high platform independence, sometimes our applications still need to interact with the underlying operating system (OS). This chapter introduces several ways to communicate with the operating system in Java.

System Properties

System properties are a collection of information about the Java runtime environment and current operating system configuration. The JVM initializes these properties at startup. You can access them through the System class.

  • System.getProperties(): Returns a Properties object containing all system properties.
  • System.getProperty(key): Gets the system property value for the specified key.

Common System Property Keys:

KeyDescription
java.versionJava runtime environment version
java.homeJava installation directory
os.nameOperating system name
os.versionOperating system version
user.nameCurrent user's account name
user.homeCurrent user's home directory
user.dirUser's current working directory
file.separatorFile separator (/ on UNIX, \ on Windows)
java
public class SystemPropertiesExample {
    public static void main(String[] args) {
        // Get a single system property
        String osName = System.getProperty("os.name");
        String userHome = System.getProperty("user.home");
        String javaVersion = System.getProperty("java.version");

        System.out.println("Operating System: " + osName);
        System.out.println("User Home Directory: " + userHome);
        System.out.println("Java Version: " + javaVersion);

        // Print all system properties
        // System.getProperties().list(System.out);
    }
}

Environment Variables

Environment variables are dynamically named values maintained by the operating system that can affect the behavior of running processes. Unlike system properties, environment variables are independent of the JVM and are system-level configurations.

  • System.getenv(): Returns an unmodifiable Map<String, String> containing all environment variables.
  • System.getenv(name): Gets the value of the environment variable with the specified name.
java
import java.util.Map;

public class EnvironmentVariableExample {
    public static void main(String[] args) {
        // Get a single environment variable (e.g., PATH)
        String pathVar = System.getenv("PATH");
        System.out.println("PATH environment variable: " + pathVar);

        // Iterate through all environment variables
        // Map<String, String> envMap = System.getenv();
        // for (String envName : envMap.keySet()) {
        //     System.out.format("%s=%s%n", envName, envMap.get(envName));
        // }
    }
}

Executing External Commands

Java allows you to execute operating system commands from within your application. In modern Java, it's recommended to use the ProcessBuilder class because it provides more control and flexibility than the older Runtime.exec() method.

Using ProcessBuilder

The basic steps for ProcessBuilder are as follows:

  1. Create a ProcessBuilder instance and pass in the command and its arguments.
  2. (Optional) Configure the working directory, environment variables, redirect input/output streams, etc.
  3. Call the start() method to execute the command, which returns a Process object.
  4. Interact with the running process through the Process object, such as waiting for it to complete or reading its output.
java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class ExecuteCommandExample {
    public static void main(String[] args) {
        // Determine the current operating system
        boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");

        // Create ProcessBuilder object
        ProcessBuilder processBuilder = new ProcessBuilder();

        // Set different commands based on the operating system
        if (isWindows) {
            // Execute 'dir' command on Windows
            processBuilder.command("cmd.exe", "/c", "dir");
        } else {
            // Execute 'ls -l' on macOS/Linux
            processBuilder.command("sh", "-c", "ls -l");
        }

        try {
            // Start the process
            Process process = processBuilder.start();

            // Read the standard output of the command
            StringBuilder output = new StringBuilder();
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            // Wait for the process to complete and get the exit code
            int exitCode = process.waitFor();
            System.out.println("\nCommand execution completed, exit code: " + exitCode);
            System.out.println("Command output:");
            System.out.println(output);

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Using ProcessBuilder makes it very convenient to execute system commands, run scripts, or call other command-line tools, integrating your Java application with the broader system environment.

Content is for learning and research only.