【发布时间】:2015-12-17 02:24:42
【问题描述】:
import java.io.*;
import java.io.IOException;
import java.util.Scanner;
public class AutoStart{
public static void main(String[] args){
while(true){
Runtime r = Runtime.getRuntime();
try{
Process p = r.exec("ps -ef >> services.txt");
try{
p.waitFor();
} catch(InterruptedException e){
e.getStackTrace();
}
Scanner txtscan = new Scanner(new File("services.txt"));
int running = 0; //0 means not running and 1 means running
while(txtscan.hasNextLine()){
String str = txtscan.nextLine();
if(str.indexOf("red5") != -1){
running = 1;
}
}
if(running == 0){
//red5 is not running so start it now
//code to start it goes here
}
//at the end remove services.txt file
//code to remove that file goes here.
} catch(IOException e){
e.getStackTrace();
}
try {
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}
在第 10 行,我正在尝试创建一个文本文件,其中包含所有正在运行的程序的列表,但我的 java 程序无法创建它。
这个程序无法创建 services.txt 文件,我根本没有收到任何错误,所以我很困惑是什么问题。你能帮我找出问题吗?谢谢你。
【问题讨论】:
-
您是否只需要 services.txt 来将数据从命令输出传递到您的 Java 程序?最好使用 p.getInputStream() 或 p.getErrorStream() 代替
-
强烈建议使用完整路径名 (/bin/ps),因为不支持 PATH 设置。重定向也不起作用。 ProcessBuilder 类提供了读取或重定向程序输出的方法。
-
1.不要使用 Runtime.exec(),使用 ProcessBuilder。 2. 它们中的任何一个都不会在 shell 解释器中发出命令,这就是为什么你的命令不起作用(
>> xxx由命令解释器解释;但这里这些是ps命令的参数,其中当然,对他们一无所知。)。