在linux如何在程序中调用shell命令启动另一个程序

来源:互联网 发布:美联储通胀数据 编辑:程序博客网 时间:2024/06/10 04:46

背景知识:Java语言以其跨平台性和简易性而著称,在Java里面的lang包里(java.lang.Runtime)提供了一个允许Java程序与该程序所运
行的环境交互的接口,这就是Runtime类,在Runtime类里提供了获取当前运行环境的接口。
其中的exec函数返回一个执行shell命令的子进程。exec函数的具体实现形式有以下几种:
public Process exec(String command) throws IOException
public Process exec(String command,String[] envp) throws
IOException
public Process exec(String command,String[] envp,File dir) throws
IOException
public Process exec(String[] cmdarray) throws IOException
public Process exec(String[] cmdarray, String[] envp) throws
IOException
public Process exec(String[] cmdarray, String[] envp,File dir)
throws IOException
??
我们在这里主要用到的是第一个和第四个函数,具体方法很简单,就是在exec函数中传递一个代表命令的字符串。exec函数返回的是一个Process类
型的类的实例。Process类主要用来控制进程,获取进程信息等作用。(具体信息及其用法请参看Java doc)。

 

解决问题:

我需要编写一个段程序,需要通过它启动和linux下的tomcat程序,tomcat启动的shell命令在/usr/local/tomcat/apache-tomcat-7.0.29/bin下的startup.sh命令,所以只需要使用尚明的exec函数执行"/usr/local/tomcat/apache-tomcat-7.0.29/bin/startup.sh"字符串就可以了,代码如下:

 

import java.io.*;import java.lang.*;public class hello{public static  void main(String[] args){//system("ls -a");try{String com="/usr/local/tomcat/apache-tomcat-7.0.29/bin/startup.sh";Process process = Runtime.getRuntime().exec (com);}catch(Exception e){System.out.println("err");}System.out.println("this is a test");}}