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 + "\n"); } 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
相关文章
- java.rmi.NoSuchObjectException: no such object in table
- MySQL_(Java)【连接池】简单在JDBCUtils.java中创建连接池
- Java实现 LeetCode 556 下一个更大元素 III(数组的翻转)
- Java实现 LeetCode 450 删除二叉搜索树中的节点
- Java实现 LeetCode 109 有序链表转换二叉搜索树
- java实现括号的匹配
- Java实现第八届蓝桥杯9算数式
- java实现第六届蓝桥杯无穷分数
- Java中IO软件包的详细介绍
- [Java] JDK 系统环境变量设置 bat
- Eclipse 报 “Exception in thread "main" java.lang.OutOfMemoryError: Java heap space ”错误的解决办法
- Java 过滤特殊字符的 正则表达式
- Atitit java播放器调音速率快慢的实现 目录 1.1. 原理 本质上是改变采样率即可1 2. 使用Java增加/降低AudioInputStream的音频播放速度(Increase/dec
- Atitit.java jar hell解决方案-----Djava.ext.dirs in ide envi..
- Java通过socket和DTU,RTU连接工业传感器通信
- What is the reason for - java.security.spec.InvalidKeySpecException: Unknown KeySpec type: java.security.spec.ECPublicKeySpec
- jackson 序列化忽略未知字段: How to Ignore Unknown Properties While Parsing JSON in Java
- Java学习笔记六(I/O流)
- 算法 《霍纳的方法java实践》
- Java开发篇——浅谈数据结构和算法(1)
- java数组排序,升序和降序
- 【java】Java 封装