Java calls methods of Shell commands

  • 2020-04-01 04:03:54
  • OfStack

This article illustrates how Java invokes Shell commands. Share with you for your reference. The details are as follows:

Recently, there is a requirement in the project: after the foreign currency fund scheduling in the system is completed, the scheduling information should be generated into a Txt file, which is then sent to another system (Kondor). OutputStreamWirter is used to generate files naturally. There are two ways to send files. One is to write a program similar to FTP function, and the other is to use Java to call the Shell and send the files in the Shell. We choose the latter, that is, when the foreign currency funds are scheduled, using Java OutputStreamWriter to generate a Txt file, and then using Java to call the Shell script, in the Shell script to complete the FTP file to the Kondor system.

The following Java program 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 {
//The basic path
private static final String basePath = "/tmp/";
//The location of the log file that records the Shell's execution (absolute path)
private static final String executeShellLogFile = basePath + "executeShell.log";
//The file name of the Shell that sends the file to Kondor (absolute path)
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;
//Format date and time for logging
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");
try {
stringBuffer.append(dateFormat.format(new Date())).append(" To prepare Execute Shell command ").append(shellCommand).append(" /r/n");
Process pid = null;
String[] cmd = {"/bin/sh", "-c", shellCommand};
//Execute Shell command
pid = Runtime.getRuntime().exec(cmd);
if (pid != null) {
stringBuffer.append(" The process no. : ").append(pid.toString()).append("/r/n");
//BufferedReader = new bufferedReader (new InputStreamReader(pid.getinputstream ()), 1024);
pid.waitFor();
} else {
stringBuffer.append(" There is no pid/r/n");
}
stringBuffer.append(dateFormat.format(new Date())).append("Shell Order executed /r/n The execution result is: /r/n");
String line = null;
//The output of the Shell is read and added to the stringBuffer
while (bufferedReader != null &
&
(line = bufferedReader.readLine()) != null) {
stringBuffer.append(line).append("/r/n");
}
} catch (Exception ioe) {
stringBuffer.append("Execute Shell command When abnormal: /r/n").append(ioe.getMessage()).append("/r/n");
} finally {
if (bufferedReader != null) {
OutputStreamWriter outputStreamWriter = null;
try {
bufferedReader.close();
//Output the Shell's execution to a log file
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;
}
}

Here is the Shell script sendkondorfile.sh, which FTP the file to the specified location:


#!/bin/sh
# The location of the log file 
logFile="/opt/fms2_kondor/sendKondorFile.log"
#Kondor Of the system IP The address to which the generated file is sent 
kondor_ip=192.168.1.200
#FTP The user name 
ftp_username=kondor
#FTP password 
ftp_password=kondor
# The absolute path to the file to be sent 
filePath=""
# The file name of the file to be sent 
fileName=""
# if Shell The command takes an argument and assigns the first argument to filePath , assign the second parameter to fileName
if [ $# -ge "1" ]
then
filePath=$1
else
echo " No file path "
echo " No file path /n" >
>
$logFile
return
fi
if [ $# -ge "2" ]
then
fileName=$2
else
echo " No file name "
echo " No file name /n" >
>
$logFile
return
fi
echo " The file to send is  ${filePath}/${fileName}"
cd ${filePath}
ls $fileName
if (test $? -eq 0)
then
echo " Ready to send documents: ${filePath}/${fileName}"
else
echo " file  ${filePath}/${fileName}  There is no "
echo " file  ${filePath}/${fileName}  There is no /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`  Sent the file  ${filePath}/${fileName}"
echo "`date +%Y-%m-%d' '%H:%M:%S`  Sent the file  ${filePath}/${fileName}/n" >
>
$logFile

The method is:


JavaShellUtil javaShellUtil = new JavaShellUtil();
//The argument is the Shell command to execute, which is to send the tmp.pdf file in the /temp directory to 192.168.1.200 by calling the Shell script sendkondorfile.sh
int success = javaShellUtil.executeShell("sh /tmp/sendKondorFile.sh /temp tmp.pdf");

I hope this article has been helpful to your Java programming.


Related articles: