• Executing System commands in Java---ref


    One of the nice features of Java language is that it provides you the opportunity to execute native system commands and in this tutorial we will see how to use Runtime class in a quite simple program to execute commands like ipconfig

    As an example consider the below snippet

    package com.javaonly.system;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class SystemCommandsTest {
    
        public static void main(String args[]) {
            StringBuffer output = new StringBuffer();
            try {
                Process process = Runtime.getRuntime().exec(
                        "ipconfig");
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        process.getInputStream()));
    
                String line = "";
                while ((line = reader.readLine()) != null) {
                    output.append(line + "
    ");
                }
                System.out.println("OUTPUT:"+output.toString());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        }
    }

    As you can see in the above class we first need to access the runtime environment.This is done with

    Runtime.getRuntime()

    method.We also need to create an OS process in order to execute the system command. As you can see this process is created with

    exec()

    method of the Runtime class.Finally we need to create a BufferedReader in order to read the input stream of the process and display the output in our console.

    Executing ipconfig command will give us the below output

    OUTPUT:
    
    Windows IP Configuration
    
    Ethernet adapter Local Area Connection 2:
    
    
    
            Connection-specific DNS Suffix  . : 
    
            IP Address. . . . . . . . . . . . : 192.168.2.3
    
            Subnet Mask . . . . . . . . . . . : 255.255.255.0
    
            Default Gateway . . . . . . . . . : 192.168.2.1

    ref:http://www.java-only.com/LoadTutorial.javaonly?id=117

  • 相关阅读:
    查看Sql Server2016 是否激活
    MSSQL 账户访问视图权限的设置
    Vue 前端验证码
    (攻防世界) -- pwn入门 -- 新手区1 -- CGfsb
    .NET Core自动注册服务
    C# Graphics 生成文字圆形头像
    Codeforces Round #729 (Div. 2) C. Strange Function
    Codeforces Round #710 (Div. 3) ABCDE 题解
    Codeforces Round #708 (Div. 2) ABC1C2题解
    Codeforces Round #706 (Div. 2) D. Let's Go Hiking 博弈 思维
  • 原文地址:https://www.cnblogs.com/davidwang456/p/3756776.html
Copyright © 2020-2023  润新知