Overview

最近需要用到数个Python程序处理蛋白质序列以输出特征值,而这些Python文件需要在Shell脚本中传入文本文件(该文本文件记录了某些蛋白质序列)做参数,进而依次被Shell调用。我们在Java程序中建立Shell脚本的运行时环境Runtime,这其中用到了一个类,即java.lang.Runtime,下面对该类进行探讨和记录。

1.直接运行Shell命令

java.lang.Runtime类有一个特点,官方文档说明如下:

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.
An application cannot create its own instance of this class.

大意就是:Java程序不能实例化(所以也没有构造方法),如需获取当前的运行环境只能通过无参的getRuntime()方法,该方法返回值为Runtime,进而使用它的exec(String command)或者exec(String[] cmdarray),返回一个Process。代码如下:

Process process;
List<String> processList = new ArrayList<String>();  
try {  
    process = Runtime.getRuntime().exec(“pwd”);
    BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));  
    String line = "";  
    while ((line = input.readLine()) != null) {  
        processList.add(line);  
    }  
    input.close();  
} catch (IOException e) {  
    e.printStackTrace();  
}  
for (String line : processList) {  
    System.out.println(line);  
} 

"pwd"命令运用之后,帮助我们得到当前的工作目录为/root,从而为下一步执行Shell脚本文件也提供了有利条件。

2.执行Shell脚本文件

Runtimeexec()方法还有另外一种重载形式exec(String[] cmdarray, String[] envp, File dir),其作用更为强大,开发人员可以将命令全部写入脚本文件,使得命令连续执行,而且可以指定脚本文件的工作目录。

public void read(String str) throws NullPointerException{  
                            
    String command = "/bin/bash" + " " + ServletActionContext.getServletContext().getRealPath("/") + "useful_scripts/feature_calc.sh"+" "+str;
    File dir = new File(ServletActionContext.getServletContext().getRealPath("/") + "useful_scripts");
    System.out.println(command);//测试command命令
    Process process;
    List<String> processList = new ArrayList<String>();  
    try {  
        process = Runtime.getRuntime().exec(command, null, dir);//环境变量通常为null,表明使用当前环境。
        BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));  
        String line = "";  
        while ((line = input.readLine()) != null) {  
            processList.add(line);  
        }  
        input.close();  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  
  
    for (String line : processList) {  
        System.out.println(line);  
    }  
}

其中有一点需要注意:dir参数类型是File,但是官方文档解释为“工作目录”,故用法如下:

File dir = new File("你的工作目录的路径")