利用Runtime.execute方法,我们可以在Java程序中运行Linux的Shell脚本,或者执行其他程序。参考了互联网上的这篇文章:http://lee79.javaeye.com/blog/418549(感谢一下),我重新整理了代码。
现在通过CommandHelper.execute方法可以执行命令,该类实现代码如下:
package javaapplication3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* @author chenshu
*/
public class CommandHelper {
//default time out, in millseconds
public static int DEFAULT_TIMEOUT;
public static final int DEFAULT_INTERVAL = 1000;
public static long START;
public static CommandResult exec(String command) throws IOException, InterruptedException {
Process process = Runtime.getRuntime().exec(command);
CommandResult commandResult = wait(process);
if (process != null) {
process.destroy();
}
return commandResult;
}
private static boolean isOverTime() {
return System.currentTimeMillis() - START >= DEFAULT_TIMEOUT;
}
private static CommandResult wait(Process process) throws InterruptedException, IOException {
BufferedReader errorStreamReader = null;
BufferedReader inputStreamReader = null;
try {
errorStreamReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
inputStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
//timeout control
START = System.currentTimeMillis();
boolean isFinished = false;
for (;;) {
if (isOverTime()) {
CommandResult result = new CommandResult();
result.setExitValue(CommandResult.EXIT_VALUE_TIMEOUT);
result.setOutput("Command process timeout");
return result;
}
if (isFinished) {
CommandResult result = new CommandResult();
result.setExitValue(process.waitFor());
//parse error info
if (errorStreamReader.ready()) {
StringBuilder buffer = new StringBuilder();
String line;
while ((line = errorStreamReader.readLine()) != null) {
buffer.append(line);
}
result.setError(buffer.toString());
}
//parse info
if (inputStreamReader.ready()) {
StringBuilder buffer = new StringBuilder();
String line;
while ((line = inputStreamReader.readLine()) != null) {
buffer.append(line);
}
result.setOutput(buffer.toString());
}
return result;
}
try {
isFinished = true;
process.exitValue();
} catch (IllegalThreadStateException e) {
// process hasn't finished yet
isFinished = false;
Thread.sleep(DEFAULT_INTERVAL);
}
}
} finally {
if (errorStreamReader != null) {
try {
errorStreamReader.close();
} catch (IOException e) {
}
}
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
}
}
}
}
}
CommandHelper类使用了CommandResult对象输出结果错误信息。该类实现代码如下:
package javaapplication3;
/**
*
* @author chenshu
*/
public class CommandResult {
public static final int EXIT_VALUE_TIMEOUT=-1;
private String output;
void setOutput(String error) {
output=error;
}
String getOutput(){
return output;
}
int exitValue;
void setExitValue(int value) {
exitValue=value;
}
int getExitValue(){
return exitValue;
}
private String error;
/**
* @return the error
*/
public String getError() {
return error;
}
/**
* @param error the error to set
*/
public void setError(String error) {
this.error = error;
}
}
现在看看调用代码的演示(main函数接受一个超时参数):
public static void main(String[] args) {
try {
int timeout = Integer.parseInt(args[0]);
CommandHelper.DEFAULT_TIMEOUT = timeout;
CommandResult result = CommandHelper.exec("mkdir testdir");
if (result != null) {
System.out.println("Output:" + result.getOutput());
System.out.println("Error:" + result.getError());
}
} catch (IOException ex) {
System.out.println("IOException:" + ex.getLocalizedMessage());
} catch (InterruptedException ex) {
System.out.println("InterruptedException:" + ex.getLocalizedMessage());
}
}
结果会创建一个testdir目录。
我尝试用这种方法创建通过ssh登录到远程机器,遇到两个问题:
1)如果希望没有人机对话方式,则需要使用命令sshpass -p password ssh user@targetIP 'command'
2) 在NetBeans上直接运行工程是不行的,因为权限不够,需要在终端里运行java javaapplication3.Main
3) 很多命令不能运行,只有如pwd等命令可以运行,原因还不清楚,最好改用Ganymed SSH-2库或者其他类似Java库,我会在下一篇文章中介绍如何使用。
分享到:
相关推荐
java调用shell 包含简单的编写shell文件 调用含有参数的shell文件
java调用shell脚本java调用shell脚本java调用shell脚本java调用shell脚本java调用shell脚本java调用shell脚本
在Java程序中调用Unix/Linux主机上的Shell命令,并返回相应执行结果。
在java代码中调用执行shell脚本,sqlldr导数与使用sqlplus在shell调用执行存储过程。 linux环境中有2个dba的用户:oracle、erm 还有1个web用户:erm 在linux环境中,这三个用户都可以直接在任意目录下执行该shell...
利用Runtime.execute方法,我们可以在Java程序中运行Linux的Shell脚本,或者执行其他程序
shell,bat脚本运行java程序, shell,bat脚本运行java程序,
shell脚本启动Java程序测试工程
详细的linux shell脚本启动java代码类。
linux中java项目需要重启一般使用先找到进程杀掉进程,然后找到项目启动,整个过程不算复杂,但是每次都操作一遍太麻烦,我这里把这个过程整理成shell脚本,大家可以修改里面项目名称,每次直接执行这个命令重启项目...
cat /mnt/log_function.sh #!/bin/bash #log function ####log_correct函数打印正确的输出到日志文件 function log_correct () { DATE=`date “+%Y-%m-%d %H:%M:%S”` ####显示打印日志的时间...log_error打印shell脚本
该工具包可实现远程调用Shell脚本,可帮助您轻松实现java远程调用Shell脚本
在 Java 中调用 Shell 命令是非常常见的操作,特别是在需要执行系统命令或脚本时。在这个例子中,我们将看到如何使用 Java 调用 Shell 命令,并介绍相关的知识点。 Java 调用 Shell 命令的必要性 在实际开发中,...
在开发过程中经常会员到在Linux环境中使用Shell脚本启动和停止java程序的情况,常用的java -jar命令只能运行jar文件,有很多不方便的地方,一旦代码修改就需要重新编辑打包,其实还有很多其他的方式,这个资源中包含...
linux shell脚本启动java。 ---------------------------------------- Windows编辑的sh,在linux会报错: shell unexpected end of file 解决办法: vim test.sh :set fileformat=unix :wq ----------------------...
我们选择后一种,即当完成外币资金的调度工作后,用Java的OutputStreamWriter来生成一个Txt文件,然后用Java来调用Shell脚本,在Shell脚本中完成FTP文件到Kondor系统的工作。
主要介绍了Java调用linux shell脚本的方法,需要的朋友可以参考下
java执行shell或bat脚本,Java可以使用三种方式来执行.bat或.shell脚本文件:使用Runtime.exec()、使用ProcessBuilder、使用第三方工具包commonsexec.jar
第一次接触linux系统,之前写的数据导出不好使了。...找了好多资料,最后决定写个shell脚本;没接触过shell脚本,网上大部分例子都写的挺复杂的;贴个简单的,不带传参什么的;只是最简单的数据表的导出备份
java连接服务器,并执行Linux服务器上的命令或脚本