【问题标题】:Process doesn't return it's output进程不返回它的输出
【发布时间】:2018-12-08 09:52:09
【问题描述】:

我编写了一个简单的 AppleScript,并尝试从 Java 调用该进程,该进程将使用 osascript 来运行实际脚本。该脚本似乎已执行,但没有输出任何内容。我尝试从终端运行相同的脚本,它按预期工作 - 我得到了类似 {{300, 450}, {500, 500}} 的输出。

    public void macTest() throws ScriptException, IOException, InterruptedException {
        final String script= "tell application \"System Events\" to tell application process \"Eclipse\"\n" + 
                "   get {size, position} of window 1\n" + 
                "end tell";

        System.out.println(runProcess(String.format("osascript -e '%s'", script)));
    }

    public static String runProcess(String cmdline) throws IOException, 
    InterruptedException { 
        Process p = Runtime.getRuntime().exec(cmdline); 
        p.waitFor(); 
        try { 
            return readContents(p.getInputStream()); 
        } finally { 
            p.destroy(); 
        } 
    } 

    public static String readContents(InputStream inputStream) 
            throws IOException { 
        StringBuilder contents = new StringBuilder(); 
        BufferedReader reader = new BufferedReader(new InputStreamReader( 
                inputStream)); 
        try { 
            String line; 
            while ((line = reader.readLine()) != null) {
                contents.append(line).append("\n"); 
            } 
        } finally { 
            reader.close(); 
        } 
        return contents.toString().trim(); 
    } 

这里的输入流好像是空的。如何在 Java 中获取我的进程的输出?

【问题讨论】:

  • p.getErrorStream() 中有什么内容?看那里。
  • 一个提示是尝试 AppleScript 的单行版本,如下所示:"tell application \"System Events\" to tell application process \"Eclipse\" to get {size, position} of window 1"(不需要end tell)。

标签: java process io applescript


【解决方案1】:

从 Java 调用系统进程可能有点棘手:意识到隐式多线程正在运行:

  • 一方面,您的 Java 程序在 JVM(一个进程)上运行。
  • 另一方面,您启动的子进程独立于 JVM 运行。这个过程肯定会将数据写入其输出流和/或错误流(甚至可能从其输入流中读取数据,但情况似乎并非如此)。

简而言之:您必须启动一个线程来读取子进程的输出流(通过您的readContents方法)并启动另一个线程来读取子进程的错误流。而且,一旦它们启动,您可以调用waitFor 方法来阻塞主线程,直到子进程结束。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多