java如何运行linux命令


 

  • javac TestRunTime.java
  • java TestRunTime hostname // 执行“hostname”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<args.length; 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());
        }
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM