通过Java代码从Mac OS终端窗口读取文本?

时间:2016-02-11 10:11:54

标签: java macos terminal

这是我正在使用的代码:

String cmd="tell application \"Terminal\" to do script \"cd  "+ path +" && "+ command +" \" ";
System.out.println(cmd);
ProcessBuilder builder = new ProcessBuilder("osascript","-e",cmd);
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));

它给出了null。如何从终端窗口读取?

1 个答案:

答案 0 :(得分:0)

您可以使用Apache Commons Exec完成此操作。

import java.io.ByteArrayOutputStream;
import org.apache.commons.exec.*;

class CMDTest {
    public static void main(String[] args) {
       try{
         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
         CommandLine command = new CommandLine("/bin/sh");
         command.addArguments(new String[] {
           "-c",
           "ls '-al'"
         },false);
         DefaultExecutor exec = new DefaultExecutor();
         PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
         exec.setStreamHandler(streamHandler);
         exec.execute(command);
         System.out.println(outputStream.toString());
       }
       catch(Exception e){
         System.out.println("error");
       }
    }
}