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