我正在嘗試在Java程序中打印Mac的[編輯:Apple計算機]序列號。我熟悉Unix命令ioreg -l | awk '/IOPlatformSerialNumber/ { print $4;}'在終端中完成此任務。當我嘗試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());我的序列號未打印。而是打?。?lt;+-o Root class IORegistryEntry, id 0x100000100, retain 10> 我認為問題是這terminal.exec()并不意味著要使用整個命令字符串。Java中是否有類似于shell = Truepython中的參數(shù)的東西Popen(command, stdout=PIPE, shell=True),可以讓我傳遞整個命令字符串?
3 回答

LEATH
TA貢獻1936條經(jīng)驗 獲得超7個贊
Runtime.exec(..)不支持管道,因為它們是Shell的功能。相反,您必須自己模擬管道,例如
String ioreg = toString(Runtime.exec("ioreg -l ").getInputStream());
Process awk = Runtime.exec("awk '/IOPlatformSerialNumber/ { print $4;}'");
write(awk.getOutputStream(), ioreg);
String input = new BufferedReader(new InputStreamReader(awk.getInputStream())).readLine();
另外,您當然可以將Shell作為進程運行

慕蓋茨4494581
TA貢獻1850條經(jīng)驗 獲得超11個贊
要通過Java獲取MAC地址,可以使用java.net.NetworkInterface:
NetworkInterface.getByName("xxx").getHardwareAddress()
如果您不知道網(wǎng)絡接口的名稱(我在Linux上假定為'eth0'),則甚至可以使用遍歷所有網(wǎng)絡接口NetworkInterface.getNetworkInterfaces()。
添加回答
舉報
0/150
提交
取消