Printing my Mac’s serial number in java using Unix commands

I see two possibilities:

  1. Parse the output of ioreg -l using, say, Scanner.

  2. Wrap the command in a shell script and exec() it:

#!/bin/sh
ioreg -l | awk '/IOPlatformSerialNumber/ { print $4;}'

Addendum: As an example of using ProcessBuilder, and incorporating a helpful suggestion by Paul Cager, here’s a third alternative:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class PBTest {

    public static void main(String[] args) {
        ProcessBuilder pb = new ProcessBuilder("bash", "-c",
            "ioreg -l | awk '/IOPlatformSerialNumber/ { print $4;}'");
        pb.redirectErrorStream(true);
        try {
            Process p = pb.start();
            String s;
            // read from the process's combined stdout & stderr
            BufferedReader stdout = new BufferedReader(
                new InputStreamReader(p.getInputStream()));
            while ((s = stdout.readLine()) != null) {
                System.out.println(s);
            }
            System.out.println("Exit value: " + p.waitFor());
            p.getInputStream().close();
            p.getOutputStream().close();
            p.getErrorStream().close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Leave a Comment