Java/Ruby/C程序调用Shell脚本的方法

JAVA中

protected void onPostExecute(Integer result) {
   if (bBackground) {
    // 启动安装程序
    if (0 == result) {
     String path = FileUtils.getSDPATH(HActivity.this)
       + "mapp.apk";
     chmod("777", path);
     File apkFile = new File(path);
     if (apkFile.exists()) {
      Intent intent = new Intent(Intent.ACTION_VIEW);
      intent.setDataAndType(Uri.fromFile(apkFile),
        "application/vnd.android.package-archive");
      startActivity(intent);
     }
    }
   } else {
    resultFile(result);
   }
  }
 
 
private static void chmod(String permission, String path) {
  try {
   String command = "chmod " + permission + " " + path;
   Runtime runtime = Runtime.getRuntime();
   runtime.exec(command);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

在Linux环境下工作的话,Shell脚本是经常用到,在很多其他 程序中都有可能调用到。被人问到,怎样在Ruby程序中调用Shell脚本;经过总结整理,我分别说明一下如何在Ruby、C、Java代码中怎样调用 shell脚本吧。

Ruby中调用Shell有很多种方 法;下面代码简单说明一下吧。

// 第一种 用反引号将shell命令引起来,如果是shell脚本可写上绝对路径(总之就是可以直接运行的)
ipinfo=`ifconfig`
puts ipinfo

// 第二种 用system函数来实现
system 'echo "hello $HOSTNAME"'

// 第三种 用IO类的popen方法
IO.popen("date") { |f| puts f.gets }

// 第四种 用Ruby标准库open3中的方法
require "open3"
stdin, stdout, stderr = Open3.popen3('date')
stdin.puts('')
stdout.gets
stderr.gets
其实还有其他一些方式,这里有篇博客写了Ruby调用shell的六种方法:
http://blackanger.blog.51cto.com/140924/43730

C程序中调用shell脚本,一般通过system函数来执行shell脚本。参考代 码如下:
#include   <stdlib.h>
int main(int argc, char* argv[])
{
    system("echo 'hello world'");
    system("/bin/ls /home");
}
更多详细内容,可查一下system函数的用法。

Java中调用Shell脚本,一般通过运行时类Runtime的方法来实现 (Runtime.getRuntime().exec),参考代码如下:
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

public class CallShell {
    public static void main(String[] args) {
        try {
            // 被注释掉的这个仅仅是执行了test.sh脚本,但没有获取它的输出
            // Runtime.getRuntime().exec("/home/master/workspace/shell/test.sh");
            Process process = Runtime.getRuntime().exec(
                    "/home/master/workspace/shell/test.sh");
            InputStreamReader ir = new InputStreamReader(process
                    .getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String line;
            while ((line = input.readLine()) != null)
                System.out.println(line);
            input.close();
            ir.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

另外,再附带贴一个,Java调用 Shell并打印标准输出、标准错误的Java类,代码如下,供参考:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @className ShellCmdLog.java
 * @author 笑遍世界
 * @description Java程序调用一个系统的shell脚本,并且将标准输出和标准错误打印出来
 * @date 2010-11-26
*/
public class ShellCmdLog extends Thread {
    private boolean bLog2Error; // 是否打印错误Error标志
    private InputStream ins; // 待转换文件输入流

    /**
     * @param args
     */
    public static void main(String[] args) {
        // java调用shell脚本
        String path = "/home/master/workspace/shell/test.sh";// 脚本位于服务器中的路径
        String statement[] = { "/bin/sh", path };
        try {
            Process process = Runtime.getRuntime().exec(statement);
            InputStream in = process.getInputStream(); // 获取输入流
            InputStream err = process.getErrorStream();// 获取错误流

            ShellCmdLog sgStdout = new ShellCmdLog(in, false);
            ShellCmdLog sgStderr = new ShellCmdLog(err, true);

            sgStdout.start();
            sgStderr.start();

            // final int result = process.waitFor();

            // 为流读出捕获流设定的时间间隔。
            Thread.sleep(100);

            if (process != null) {
                process.destroy();
            }

            // 集合读取线程
            sgStdout.join();
            sgStderr.join();

        } catch (Exception e) {
            e.toString();
        }
    }

    /**
     * 设置是否打印错误Error,设置待转换文件的输入流
     * 
     * @param is
     *            待转换文件输入流
     * @param flag
     *            是否打印错误Error标志
     */
    
    public ShellCmdLog(InputStream is, boolean flag) {
        super("ShellCmdStream" + (flag ? "-error" : "-out"));
        bLog2Error = flag;
        ins = is;
    }

    /**
     * 执行转换线程
     */
    public void run() {
        if (ins != null) {
            InputStreamReader isr = new InputStreamReader(ins);
            BufferedReader br = new BufferedReader(isr);
            try {
                String line = null;
                while ((line = br.readLine()) != null) {
                    if (bLog2Error) {
                        System.out.println("Shell_Err>" + line);
                    } else {
                        System.out.println("Shell_Out>" + line);
                    }
                } // end of while(true)
            } catch (IOException ioe) {
                System.out.println("ShellCmdLog error:" + ioe);
            } finally {
                try {
                    if (isr != null) {
                        isr.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (br != null) {
                        br.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

猜你喜欢

转载自huaonline.iteye.com/blog/1751114