java - 使用 BufferedReader 在 java 中读取终端命令的输出

标签 java terminal ifconfig output

新手在 java 刚开始,将不胜感激任何帮助。所以我的代码是这样的,出于某种原因我无法让输出正常工作..我已经坐了几个小时了..

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



} 

最佳答案

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

关于java - 使用 BufferedReader 在 java 中读取终端命令的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13000412/

相关文章:

linux - 我有一些代码有一个在终端上运行良好但从脚本运行时失败的命令

php - 在 Yii 中通过命令执行 shell

windows - 为什么 “ifconfig” docker 命令在 Windows 上响应 "bash: ifconfig: command not found"?

linux - 公开共享 ifconfig 信息会危险吗?

linux - 连接到 WEP wifi 时没有 DHCP 响应

java - JavaFX 3D 中的可见光源

java - Android Studio java 文件损坏

java - @Autowired 存储库为空

java - Ehcache - 使用 RMI 的复制缓存

video - 提取没有音频的视频ffmpeg