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

我想要一个简单的命令,它可以从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运行后是否有可能杀死程序?

为什么这不起作用?

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

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

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

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

 public void startSOfficeService()抛出InterruptedException,IOException {
         //首先我们需要检查soffice进程是否正在运行
         String commands =“pgrep soffice”;
         Process process = Runtime.getRuntime()。exec(commands);
         //需要等待此命令执行
         int code = process.waitFor();

         //如果我们从readLine返回任何内容,那么我们就知道该进程正在运行
         BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
         if(in.readLine()== null){
             //什么都没有回来,那么我们应该执行这个过程
             process = Runtime.getRuntime()。exec(“/ etc / init.d / soffice.sh”);
             code = process.waitFor();
             log.debug(“soffice script started”);
         } else {
             log.debug(“soffice脚本已经在运行”);
         }

        附寄();
     }

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

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

请注意,这仅适用于Linux。

我相信你没有正确处理引用。 原始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,我没有测试过这个!)

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

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