gpt4 book ai didi

Java程序无法执行终端命令

转载 作者:行者123 更新时间:2023-11-30 03:15:44 25 4
gpt4 key购买 nike

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 文件,而且我根本没有收到任何错误,所以我很困惑到底出了什么问题。你能帮我解决这个问题吗?谢谢。

最佳答案

这会调用子进程,而不依赖于任何 shell 机制,捕获结果标准输出。

public static void main( String[] args ) throws Exception {
try {
ProcessBuilder pb = new ProcessBuilder( "/bin/ps", "-ef" );
Process process = pb.start();
InputStream is = process.getInputStream();
Reader rdr = new InputStreamReader( is );
LineNumberReader lnr = new LineNumberReader(rdr);
String line;
while( (line = lnr.readLine()) != null ){
if( line.contains( "skype" ) ){
System.out.println( "skype is running" );
}
}
process.waitFor();
} catch( Exception e ){

} catch( Error e ){

}

关于Java程序无法执行终端命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32677387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com