从Java启动OpenOffice服务(soffice)的问题(命令行中的命令,但不是Java)

时间:2008-12-18 16:10:46

标签: java command openoffice.org runtime.exec soffice

我想要一个简单的命令,它可以从shell运行,但不能用于Java。 这是我想要执行的命令,工作正常:

soffice -headless "-accept=socket,host=localhost,port=8100;urp;" 

这是我试图运行此命令的Java代码:

String[] commands = new String[] {"soffice","-headless","\"-accept=socket,host=localhost,port=8100;urp;\""};
Process process = Runtime.getRuntime().exec(commands)
int code = process.waitFor();
if(code == 0)
    System.out.println("Commands executed successfully");

当我运行这个程序时,我得到“命令执行成功”。 但是,当程序完成时,该过程不会运行。 JVM是否有可能在程序运行后终止程序?

为什么这不起作用?

4 个答案:

答案 0 :(得分:2)

我不确定我是不是错了,但据我所知,你正在生成命令,但从未将它们传递给“执行”方法......你正在执行“”。

尝试使用Runtime.getRuntime()。exec(commands)=)

答案 1 :(得分:1)

我想说我是如何解决这个问题的。 我创建了一个sh脚本,基本上为我运行了soffice的命令。

然后从Java我运行脚本,它工作正常,像这样:

public void startSOfficeService() throws InterruptedException, IOException {
        //First we need to check if the soffice process is running
        String commands = "pgrep soffice";
        Process process = Runtime.getRuntime().exec(commands);
        //Need to wait for this command to execute
        int code = process.waitFor();

        //If we get anything back from readLine, then we know the process is running
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        if (in.readLine() == null) {
            //Nothing back, then we should execute the process
            process = Runtime.getRuntime().exec("/etc/init.d/soffice.sh");
            code = process.waitFor();
            log.debug("soffice script started");
        } else {
            log.debug("soffice script is already running");
        }

        in.close();
    }

我也通过调用此方法来杀死soffice进程:

public void killSOfficeProcess() throws IOException {
        if (System.getProperty("os.name").matches(("(?i).*Linux.*"))) {
            Runtime.getRuntime().exec("pkill soffice");
        }
    }

请注意,这仅适用于Linux。

答案 2 :(得分:0)

我相信你没有正确处理引用。原始sh命令行包含双引号以防止shell解释分号。在soffice进程看到它们之前,shell将它们剥离。

在你的Java代码中,shell永远不会看到参数,因此不需要额外的双引号(使用反斜杠转义) - 它们可能会混淆soffice。

以下是删除了额外引号的代码(并且抛出了分号)

String[] commands = new String[] {"soffice","-headless","-accept=socket,host=localhost,port=8100;urp;"};
Process process = Runtime.getRuntime().exec(commands);
int code = process.waitFor();
if(code == 0) 
    System.out.println("Commands executed successfully");

(免责声明:我不懂Java,我没有测试过这个!)

答案 3 :(得分:0)

"/Applications/OpenOffice.org\ 2.4.app/Contents/MacOS/soffice.bin -headless -nofirststartwizard -accept='socket,host=localhost,port=8100;urp;StartOffice.Service'"

或者简单地转义引号也可以。我们将这样的命令提供给一个蚂蚁脚本,该脚本最终会像你上面一样在exec调用中结束。我还建议每500次转换重启一次,因为OOO没有正确释放内存(取决于你运行的版本)。

相关问题