❶ 请教个java调用shell命令操作
近日项目中有这样一个需求:系统中的外币资金调度完成以后,要将调度信息生成一个Txt文件,然后将这个Txt文件发送到另外一个系统(Kondor)中。生成文件自然使用OutputStreamWirter了,发送文件有两种方式,一种是用写个一个类似于FTP功能的程序,另外一种就是使用Java来调用Shell,在Shell中完成文件的发送操作。我们选择后一种,即当完成外币资金的调度工作后,用Java的OutputStreamWriter来生成一个Txt文件,然后用Java来调用Shell脚本,在Shell脚本中完成FTP文件到Kondor系统的工作。
以下为Java程序JavaShellUtil.java:import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class JavaShellUtil {
//基本路径
private static final String basePath = "/tmp/";
//记录Shell执行状况的日志文件的位置(绝对路径)
private static final String executeShellLogFile = basePath + "executeShell.log";
//发送文件到Kondor系统的Shell的文件名(绝对路径)
private static final String sendKondorShellName = basePath + "sendKondorFile.sh";
public int executeShell(String shellCommand) throws IOException {
int success = 0;
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = null;
//格式化日期时间,记录日志时使用
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");
try {
stringBuffer.append(dateFormat.format(new Date())).append("准备执行Shell命令 ").append(shellCommand).append(" \r\n");
Process pid = null;
String[] cmd = {"/bin/sh", "-c", shellCommand};
//执行Shell命令
pid = Runtime.getRuntime().exec(cmd);
if (pid != null) {
stringBuffer.append("进程号:").append(pid.toString()).append("\r\n");
//bufferedReader用于读取Shell的输出内容 bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);
pid.waitFor();
} else {
stringBuffer.append("没有pid\r\n");
}
stringBuffer.append(dateFormat.format(new Date())).append("Shell命令执行完毕\r\n执行结果为:\r\n");
String line = null;
//读取Shell的输出内容,并添加到stringBuffer中
while (bufferedReader != null &
&
(line = bufferedReader.readLine()) != null) {
stringBuffer.append(line).append("\r\n");
}
} catch (Exception ioe) {
stringBuffer.append("执行Shell命令时发生异常:\r\n").append(ioe.getMessage()).append("\r\n");
} finally {
if (bufferedReader != null) {
OutputStreamWriter outputStreamWriter = null;
try {
bufferedReader.close();
//将Shell的执行情况输出到日志文件中
OutputStream outputStream = new FileOutputStream(executeShellLogFile);
outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
outputStreamWriter.write(stringBuffer.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
outputStreamWriter.close();
}
}
success = 1;
}
return success;
}
}
以下是Shell脚本sendKondorFile.sh,该Shell脚本的作用是FTP文件到指定的位置:
#!/bin/sh
#日志文件的位置
logFile="/opt/fms2_kondor/sendKondorFile.log"
#Kondor系统的IP地址,会将生成的文件发送到这个地址
kondor_ip=192.168.1.200
#FTP用户名
ftp_username=kondor
#FTP密码
ftp_password=kondor
#要发送的文件的绝对路径
filePath=""
#要发送的文件的文件名
fileName=""
#如果Shell命令带有参数,则将第一个参数赋给filePath,将第二个参数赋给fileName
if [ $# -ge "1" ]
then
filePath=$1
else
echo "没有文件路径"
echo "没有文件路径\n" >
>
$logFile
return
fi
if [ $# -ge "2" ]
then
fileName=$2
else
echo "没有文件名"
echo "没有文件名\n" >
>
$logFile
return
fi
echo "要发送的文件是 ${filePath}/${fileName}"
cd ${filePath}
ls $fileName
if (test $? -eq 0)
then
echo "准备发送文件:${filePath}/${fileName}"
else
echo "文件 ${filePath}/${fileName} 不存在"
echo "文件 ${filePath}/${fileName} 不存在\n" >
>
$logFile
return
fi
ftp -n ${kondor_ip} <
<
_end
user ${ftp_username} ${ftp_password}
asc
prompt
put $fileName
bye
_end
echo "`date +%Y-%m-%d' '%H:%M:%S` 发送了文件 ${filePath}/${fileName}"
echo "`date +%Y-%m-%d' '%H:%M:%S` 发送了文件 ${filePath}/${fileName}\n" >
>
$logFile
调用方法为:
JavaShellUtil javaShellUtil = new JavaShellUtil();
//参数为要执行的Shell命令,即通过调用Shell脚本sendKondorFile.sh将/temp目录下的tmp.pdf文件发送到192.168.1.200上
int success = javaShellUtil.executeShell("sh /tmp/sendKondorFile.sh /temp tmp.pdf");
❷ 如何在java中执行shell脚本
1、最常用的方法:
Processp=Runtime.getRuntime().exec(SHELL_FILE_DIR+RUNNING_SHELL_FILE+
""+param1+""+param2+""+param3);
intrunnngStatus=p.waitFor();
2、通过ProcessBuilder进行调度,这种方法比较直观,而且参数的设置也比较方便:
ProcessBuilderpb=newProcessBuilder("./"+RUNNING_SHELL_FILE,param1,
param2,param3);
pb.directory(newFile(SHELL_FILE_DIR));
intrunningStatus=0;
Strings=null;
try{
Processp=pb.start();
try{
runningStatus=p.waitFor();
}catch(InterruptedExceptione){
e.printStackTrace();
}
}catch(IOExceptione){
e.printStackTrace();
}
if(runningStatus!=0){
}
return;
参数说明:
RUNNING_SHELL_FILE:要运行的脚本
SHELL_FILE_DIR:要运行的脚本所在的目录; 当然你也可以把要运行的脚本写成全路径。
runningStatus:运行状态,0标识正常。 详细可以看java文档。
param1, param2, param3:可以在RUNNING_SHELL_FILE脚本中直接通过1,1,2,$3分别拿到的参数。
❸ java 调用 shell 脚本
在写程序时,有时需要在java程序中调用shell脚本,可以通过Runtime的exec方法来调用shell程序,运行脚本。每个Java 应用程序都有一个Runtime 类实例,使应用程序能够与其运行的环境相连接。通过Runtime对象可以返回运行环境的情况,包括CPU数,虚拟机内存大小等,并能够通过exec方法调用执行命令。可以通过getRuntime 方法获取当前Runtime实例。 public boolean ExeShell(){ Runtime rt = Runtime.getRuntime(); try { Process p = rt.exec(checkShellName); if(p.waitFor() != 0) return false; } catch (IOException e) { SysLog.error("没有找到检测脚本"); return false; } catch (InterruptedException e) { e.printStackTrace(); return false; } return true; } 其中p.waitFor()语句用来等待子进程结束,其返回值为进程结束退出码。
❹ 如何用java调用linux shell命令
**
* 运行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;
}
❺ 如何在java程序中调用linux命令或者shell脚本
java程序是提供了这个一方法,Processpro=Runtime.getRuntime().exec(cmds);
但是一般来说,尽量去用一些其他脚本(lua,shell,python)去执行一系列linux命令比较灵活, 而且耗费资源少。但是Runtime.getRuntime().exec()这种调用方式在java虚拟机中是十分消耗资源的,即使命令可以很快的执行完毕,频繁的调用时创建进程消耗十分可观。
java虚拟机执行这个命令的过程是,首先克隆一条和当前虚拟机拥有一样环境变量的进程,再用这个新的进程执行外部命令,最后退出这个进程。频繁的创建对CPU和内存的消耗很大。
下面是一个调用linux命令的例子:
publicclassTest{
publicstaticvoidmain(String[]args)throwsException{
String[]cmds={"/bin/sh","-c","ps-ef|grepjava"};
Processpro=Runtime.getRuntime().exec(cmds);
pro.waitFor();//阻塞,直到上述命令执行完
InputStreamin=pro.getInputStream();
BufferedReaderread=newBufferedReader(newInputStreamReader(in));
Stringline=null;
while((line=read.readLine())!=null){
System.out.println(line);
}
}
}