Java Invoke shell command method _java

Source: Internet
Author: User
Tags dateformat ftp file stringbuffer

This example describes the Java method for invoking shell commands. Share to everyone for your reference. Specifically as follows:

Recently, the project has such a demand: the system of foreign currency funds after the completion of the dispatch of the scheduling information to generate a TXT file, and then send this TXT file to another system (Kondor). Generated files are naturally used Outputstreamwirter, there are two ways to send files, one is to write a similar to the FTP function of the program, the other is to use Java to invoke the shell, in the shell to complete the sending operation of the file. We choose the latter, that is, when the foreign currency funds in the dispatch work, with the Java outputstreamwriter to generate a TXT file, and then use Java to invoke the shell script, in the shell script to complete the FTP file to the Kondor system work.

The following is the 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 {//basic path private static final String BasePath = "/tmp/";//log file location (absolute path) of the shell execution status private St
atic final String executeshelllogfile = basepath + "ExecuteShell.log";
File name (absolute path) of the shell that sent the file to the Kondor system 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 time, use DateFormat DateFormat = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:SS") when logging; try {stringbuffer.append (Dateformat.format (New Date ()). Append ("Ready to 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 ("process number:"). Append (Pid.tostring ()). Append ("/r/n");//bufferedreader to read the Shell's output
BufferedReader = new BufferedReader (New InputStreamReader (Pid.getinputstream ()), 1024);
Pid.waitfor (); else {stringbuffer.append ("no pid/r/n");} stringbuffer.append (Dateformat.format (New Date ()). Append ("shell command execution completed/
r/n execution result is:/r/n ");
String line = null; Reads the output of the shell and adds it to StringBuffer while (BufferedReader!= null & & (line = Bufferedreader.readline ())!= null) {s
Tringbuffer.append (line). Append ("/r/n"); } catch (Exception IoE) {stringbuffer.append (Exception when executing shell command:/r/n). Append (Ioe.getmessage ()). Append ("/r/n"); finally {if (BufferedReader!= null) {OutputStreamWriter outputstreamwriter = null; try {bufferedreader.close ();//Will She
ll's performance output to the 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;

 }
}

The following is the shell script sendkondorfile.sh, which acts as an FTP file to the specified location:

 #!/bin/sh #日志文件的位置 logfile= "/opt/fms2_kondor/sendkondorfile.log" #Kondor系统的IP地址, Will send the generated file to this address kondor_ip=192.168.1.200 #FTP用户名 ftp_username=kondor #FTP密码 ftp_password=kondor #要发送的文件的绝对路径 filepath= " #要发送的文件的文件名 filename= #如果Shell命令带有参数, assigns the first parameter to FilePath and assigns the second argument to the 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 filename "echo" no filename/n "&
Gt > $logFile return fi echo "The file to send is ${filepath}/${filename}" CD ${filepath} ls $fileName if (test $-eq 0) then echo "Quasi Prepare to send file: ${filepath}/${filename} "Else echo" file ${filepath}/${filename} does not exist "echo" file ${filepath}/${filename} does not exist/n "> &G
T $logFile return fi ftp-n ${kondor_ip} < < _end user ${ftp_username} ${ftp_password} ASC prompt put $fileName bye _e nd echo "' Date +%y-%m-%d '%h:%m:%s ' sent file ${filepath}/${filename}" echo "' Date +%y-%m-%d '%h:%m:%s ' sent the file ${filepath}/${ filename}/n "> > $logFile 

The Calling method is:

Javashellutil javashellutil = new Javashellutil ();
parameter is the shell command to execute, that is, to send the Tmp.pdf file in the/temp directory to the 192.168.1.200 int success by calling the shell script sendkondorfile.sh
= Javashellutil.executeshell ("Sh/tmp/sendkondorfile.sh/temp tmp.pdf");

I hope this article will help you with your Java programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.