使用Unix命令在java中打印我的Mac序列号

使用Unix命令在java中打印我的Mac序列号

本文介绍了使用Unix命令在java中打印我的Mac序列号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在java程序中打印我的mac 序列号。我熟悉Unix命令

I am trying to print my mac's [edit: Apple computer] serial number in a java program. I am familiar with the Unix command

ioreg -l | awk '/IOPlatformSerialNumber/ { print $4;}'

在终端完成此任务。

当我尝试

which accomplishes this task in terminal.
When I try

String command = "ioreg -l | awk '/IOPlatformSerialNumber/ { print $4; }'"
Runtime terminal = Runtime.getRuntime();
String input = new BufferedReader(
    new InputStreamReader(
        terminal.exec(commands).getInputStream())).readLine();
System.out.println(new BufferedReader(
    new InputStreamReader(
        terminal.exec(command, args).getInputStream())).readLine());

我的序列号未打印。而是打印:

my serial number is not printed. Instead it prints:

<+-o Root class IORegistryEntry, id 0x100000100, retain 10>

我认为问题在于 terminal.exec()并不意味着占用整个命令字符串。 java中有什么类似于参数 shell = True 在python的 Popen(命令,stdout = PIPE,shell = True)这将允许我传递整个命令字符串?

I think the problem is that terminal.exec() is not meant to take the whole command string. Is there something in java similar to the argument shell = True in python's Popen(command, stdout=PIPE, shell=True) that will allow me to pass the whole command string?

推荐答案

我看到两种可能性:


  1. 使用比如。

将命令包装在shell脚本中并且 exec() it:

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();
        }
    }
}

这篇关于使用Unix命令在java中打印我的Mac序列号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:00