如何通过Java调用系统命令,如ping 127.0.0.1、java -version等?

 

> 简单的例子

package com.nicchagil.callpython.No001无参数调用;

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


public class HowToCallSystemCommand {

    public static void main(String[] args)  {
        BufferedReader in = null;
        try {
            /* 调用、输出 */
            Process process = Runtime.getRuntime().exec("ping 127.0.0.1");
            in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            
            /* 判断是否正常 */
            int waitFor = process.waitFor();
            System.out.println("waitFor -> " + waitFor);
            if (process.waitFor() == 0) {
                System.out.println("Normal termination.");
            } else {
                System.out.println("Abnormal termination.");
            }
        } catch (Exception e) {
            // TODO
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // TODO
                    e.printStackTrace();
                }
            }
            System.out.println("Done...");
        }
    }

}
View Code

相关文章:

  • 2021-09-07
  • 2021-07-29
  • 2020-06-28
  • 2022-12-23
  • 2021-10-21
  • 2021-10-25
  • 2021-05-20
  • 2022-12-23
猜你喜欢
  • 2021-10-14
  • 2022-12-23
  • 2022-12-23
  • 2022-02-16
  • 2022-12-23
  • 2022-12-23
  • 2022-02-17
相关资源
相似解决方案