码迷,mamicode.com
首页 > 编程语言 > 详细

Executing System commands in Java---ref

时间:2014-05-29 10:27:50      阅读:316      评论:0      收藏:0      [点我收藏+]

标签:des   style   c   class   blog   code   

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

bubuko.com,布布扣
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 + "\n");
            }
            System.out.println("OUTPUT:"+output.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
bubuko.com,布布扣

 

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

bubuko.com,布布扣
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
bubuko.com,布布扣

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

Executing System commands in Java---ref,布布扣,bubuko.com

Executing System commands in Java---ref

标签:des   style   c   class   blog   code   

原文地址:http://www.cnblogs.com/davidwang456/p/3756776.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!