求高手解决这个简单的问题!!

xf2003 2004-11-02 08:22:22
java 的一个含有main(String[] arg) 的程序怎样去启动另外一个main(String[] arg) 的程序??
我在项目中写了一个GUI的程序(A),是通过 .bat( 内容是java -classpath .;XX.jar A )来运行的,但是它常常会死掉,所以,我需要另外一个程序(B,它是一个TIMER 的定时监控程序)来监控它,如果它死掉了,我就用B自动的启动它。我该这样做才可以做到这样???
...全文
91 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
xf2003 2004-11-02
  • 打赏
  • 举报
回复
本来想给你们两为大哥分的,无奈老是 抱“Service Unavailable” 错误,后续补上!
xf2003 2004-11-02
  • 打赏
  • 举报
回复
上面是我打错了,其实我的意思是 String[] command=new String[2]; 和你的意思是一样的。
2楼的程序我测试过了,OK :). 那我还想问,我该怎样结束它(B),因为我的A是一个定时启动B的程序,在启动前必须先要结束B才可以,该这么办?
xiaohaiz 2004-11-02
  • 打赏
  • 举报
回复
...那是你写得不对,单说语法,应该是:
<<
String[] command = new String[]{"java", "B"};

String[] command = new String[]{"r.bat"};
>>
xf2003 2004-11-02
  • 打赏
  • 举报
回复
谢谢,我以前也是这样的 ,但是没有你这么详细
我的程序是
String[] command=new String[];
command[0]="java";
command[1]="B";
Process child = Runtime.getRuntime().exec(command);
这样不行,然后我该成
String[] command=“r.bat”;
Process child = Runtime.getRuntime().exec(command); 还是不行,现在试试你的吧,希望可以。谢谢!!
shangqiao 2004-11-02
  • 打赏
  • 举报
回复
这样:
public class Test1 {

public static void main(String[] args) {
try {
Runtime run=Runtime.getRuntime();
Process process=null;

//必须要分清楚那些是命令(exe),哪些是程序(bat)
//process=run.exec("java");
//process=run.exec("javac");
process=run.exec("cmd.exe /c ant");
int exitValue=-1;
//<1>
//process.exitValue()将不会等待Runtime.exec()运行完毕便将运行,故得到一个异常
//exitValue=process.exitValue();
//</1>

//<2>
//process.waitFor()将无限等待下去,不会退出
//exitValue=process.waitFor();
//</2>

//<3>
InputStream errorIn=process.getErrorStream();
InputStreamReader streamReader=new InputStreamReader(errorIn);
BufferedReader bufferedReader=new BufferedReader(streamReader);
InputStream inIn=process.getInputStream();
Read readInput=new Read(inIn);
Read readError=new Read(errorIn);
Thread threadError=new Thread(readError);
Thread threadIn=new Thread(readInput);
threadIn.start();
threadError.start();
exitValue=process.waitFor();
//</3>

System.out.println("value="+exitValue);
}
catch (Exception e) {
e.printStackTrace();
}
}
}

class Read implements Runnable{
private InputStream in=null;
InputStreamReader streamReader=null;
BufferedReader bufferedReader=null;
public void run(){
try {
streamReader=new InputStreamReader(in);
bufferedReader=new BufferedReader(streamReader);
String line="";
while((line=bufferedReader.readLine())!=null){
System.out.println(line);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally{
try{
streamReader.close();
bufferedReader.close();
in.close();
}
catch(Exception e){}
}
}
public Read(InputStream in){
this.in=in;
}
}

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧