java执行shell或者cmd命令

本文介绍如何使用Java程序来执行Linux shell脚本及Windows命令,并获取执行结果。通过Runtime.getRuntime().exec()方法,文章提供了具体示例,展示了如何读取命令执行后的输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Shell: [url]http://blog.youkuaiyun.com/bhq2010/article/details/7414788[/url]
Java执行Linux命令并返回命令结果 [url]http://blog.youkuaiyun.com/jiafu1115/article/details/6941245[/url]
[color=red]使用Java中的Runtime.exec()执行Windows命令[/color] [url]http://walsh.iteye.com/blog/449051[/url]

Java 可以通过 Runtime 调用Linux命令,形式如下:
Runtime.getRuntime().exec(command)
但是这样执行时没有任何输出,因为调用 Runtime.exec 方法将产生一个本地的进程,并返回一个Process子类的实例(注意:Runtime.getRuntime().exec(command)返回的是一个Process类的实例)该实例可用于控制进程或取得进程的相关信息。
由于调用 Runtime.exec 方法所创建的子进程没有自己的终端或控制台,因此该子进程的标准IO(如stdin,stdou,stderr)都通过 Process.getOutputStream(),Process.getInputStream(), Process.getErrorStream() 方法重定向给它的父进程了。
/**
* 运行shell脚本
* @param shell 需要运行的shell脚本
*/
public static void execShell(String shell){
try {
Runtime rt = Runtime.getRuntime();
rt.exec(shell);
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 运行shell
*
* @param shStr
* 需要执行的shell
* @return
* @throws IOException
*/
public static List runShell(String shStr) throws Exception {
List<String> strList = new ArrayList();

Process process;
process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shStr},null,null);
InputStreamReader ir = new InputStreamReader(process
.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line;
process.waitFor();
while ((line = input.readLine()) != null){
strList.add(line);
}

return strList;
}



CMD: [url]http://qiaolevip.iteye.com/blog/1693623[/url]
package com.anxin.cmd.test;

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

/**
* @author: (le.qiao)
* @e-mail: qiaolevip@gmail.com
* @myblog: <a href="http://qiaolevip.iteye.com">http://qiaolevip.iteye.com</a>
* @date: 2012-10-8
*
*/
public class Command {

public static void main(String[] args) {
try {
Runtime rt = Runtime.getRuntime();
String[] args = new String[]{"cmd","/c",command};
Process pr = rt.exec(args,null,null);
//Process pr = rt.exec("cmd /c dir"); // cmd /c calc
// Process pr = rt.exec("D:\\xunlei\\project.aspx");

BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream(), "GBK"));

String line = null;

while ((line = input.readLine()) != null) {
System.out.println(line);
}

int exitVal = pr.waitFor();
System.out.println("Exited with error code " + exitVal);

} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值