4
public class LinuxInteractor {

public static String executeCommand(String command)
{
System.out.println("Linux command: " + command);

try 
{
   Process  p = Runtime.getRuntime().exec(command);
   p.waitFor();
   BufferedReader bf=new BufferedReader(new InputStreamReader( p.getInputStream()));
   String str=bf.readLine();
   System.out.println("inputStream is::"+str);
   while( (str=bf.readLine()) != null)
   {
       System.out.println("input stream is::"+str);        
   }
   System.out.println("process started");
}
catch (Exception e) {
System.out.println("Error occured while executing Linux command. Error       Description: "
    + e.getMessage());
    e.printStackTrace();
}
}

当我通过控制台运行脚本时,它正在工作。但是通过 Java 程序InputStream(Str)是作为null.

我还有其他方法可以使用吗?

4

2 回答 2

8

解决方案
您应该尝试在不同的线程上进行读取和执行。

更好的选择是使用ProcessBuilder,它会为您处理“脏”工作。
块内的代码try可能如下所示:

/* Create the ProcessBuilder */
ProcessBuilder pb = new ProcessBuilder(commandArr);
pb.redirectErrorStream(true);

/* Start the process */
Process proc = pb.start();
System.out.println("Process started !");

/* Read the process's output */
String line;             
BufferedReader in = new BufferedReader(new InputStreamReader(
        proc.getInputStream()));             
while ((line = in.readLine()) != null) {
    System.out.println(line);
}

/* Clean-up */
proc.destroy();
System.out.println("Process ended !");

另请参阅这个简短的演示


问题的 原因
根据Java Docs,:waitFor()

如有必要,使当前线程等待,直到此 Process 对象表示的进程终止。

因此,您试图在进程终止后获取进程的输出流,因此null.


(很抱歉对答案进行了重大修改。)

于 2013-06-11T07:11:17.643 回答
1

您需要在单独的线程中执行此操作:

Process process = Runtime.getRuntime().exec(command);
LogStreamReader lsr = new LogStreamReader(process.getInputStream());
Thread thread = new Thread(lsr, "LogStreamReader");
thread.start();


public class LogStreamReader implements Runnable {

    private BufferedReader reader;

    public LogStreamReader(InputStream is) {
        this.reader = new BufferedReader(new InputStreamReader(is));
    }

    public void run() {
        try {
            String line = reader.readLine();
            while (line != null) {
                System.out.println(line);
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

然后你需要第二个线程来处理输入。你可能想像处理标准输出一样处理标准错误。

于 2013-06-11T07:12:14.393 回答