【问题标题】:Reading the output of a terminal command in java with BufferedReader使用 BufferedReader 在 java 中读取终端命令的输出
【发布时间】:2012-10-21 17:41:35
【问题描述】:

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



} 

【问题讨论】:

  • 这可能与stackoverflow.com/questions/3159913/…有点重复
  • 您是否运行了该命令以确保它产生输出?
  • @WolfgangFahl 我在发布我的问题之前研究了您发布的问题,但使用该线程似乎太复杂了,因为我不熟悉 ProcessBuilder。感谢您指出这一点。
  • @jozefg 是的,该命令在终端中产生正确的输出

标签: java terminal ifconfig output


【解决方案1】:

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..

【讨论】:

    猜你喜欢
    • 2013-02-01
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多