Java: 执行Windows环境下cmd命令并打印执行结果

功能如题,上代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main
{
    public static void main(String[] strings)
    {
        System.out.println(execCommand("ipconfig"));
    }
    
    public static String execCommand(String command)
    {
        String line = "";
        StringBuilder sb = new StringBuilder();

        try (BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(
                        Runtime.getRuntime().exec(command).getInputStream()));)
        {
            while ((line = bufferedReader.readLine()) != null)
                sb.append(line + "\r\n");
        } catch (IOException e) { return "Invalid command."; }
        
        return sb.toString();
    }
}

执行效果图:

Java: 执行Windows环境下cmd命令并打印执行结果_第1张图片


在进阶的路上,欢迎各位大侠指正。

你可能感兴趣的:(Java: 执行Windows环境下cmd命令并打印执行结果)