java中如何执行linux命令

2025-05-23 03:58:28
推荐回答(4个)
回答1:

   执行linux命令基,基本思路是从控制台获得输入的指令,启动命令行执行命令,捕捉异常,示例如下:

public class TestRunTime {
 
    public static void main(String[] args) throws IOException, InterruptedException {
        String cmd = "";
        
        if(args == null || args.length == 0){
            System.out.println("请输入命令行参数");
        }else{
            
            for(int i=0;i                cmd += args[i] + " ";
            }
        }
        
 
        try {
            Process process = Runtime.getRuntime().exec(cmd);//执行命令
 
            InputStreamReader ir = new InputStreamReader(process.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
 
            String line;
            while ((line = input.readLine()) != null) {//输出结果
                System.out.println(line);
            }
        } catch (java.io.IOException e) {
            System.err.println("IOException " + e.getMessage());//捕捉异常
        }
    }
}

回答2:

Runtime.getRuntime().exec("命令");

回答3:

请问指的是linux控制台命令吗?

回答4:

链接Linux主机么? telnet 程序,百度一下全是,