3

Java 的 Noobie 刚刚开始,将不胜感激。所以我的代码是这样的,由于某种原因,我无法让输出工作..我已经坐了好几个小时了..

package askisi1;

import java.net.*;
import java.util.*;
import java.lang.*;
import java.io.*;


public class Main{

public static void main(String[] args){

    try{

        String command = "ifconfig eth1 | grep -oP '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}'";
        Process child = Runtime.getRuntime().exec(command);

        System.out.println("So far so good");
        BufferedReader r = new BufferedReader(new InputStreamReader(child.getInputStream()));
        String s;
        while ((s = r.readLine()) != null) {
        System.out.println(s);
        }
        r.close();
        System.out.println("Continue..");
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}



} 
4

1 回答 1

2

Runtime.exec()需要一些附加信息来执行 Unix 命令。

所以,假设我的以太网卡是lo0

String[] command = {
                    "/bin/sh",
                    "-c",
                    "ifconfig lo0 | grep -oP '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}'"
            }; 
Process child = Runtime.getRuntime().exec(command);
// following here your remaining unchanged code

这打印:

So far so good
127.0.0.1
Continue..
于 2012-10-21T18:00:51.680 回答