从java运行命令提示符?
嗨,我想使用java从命令提示符运行一些东西
我想转到以下目录C:\Program Files\OpenOffice.org 3\program\
然后运行soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
我试过但我无法做到这一点!
我的代码
public static void main(String[] args) { // TODO Auto-generated method stub try { Runtime rt = Runtime.getRuntime(); //Process pr = rt.exec("cmd /c dir"); // Process pr = rt.exec("cmd /c dir"); Process pr = rt.exec(new String[]{"C:\\Program Files\\OpenOffice.org 3\\program\\soffice", "-headless", "-accept='socket,host=127.0.0.1,port=8100;urp;'", "-nofirststartwizard"}); BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line=null; while((line=input.readLine()) != null) { System.out.println(line); } int exitVal = pr.waitFor(); System.out.println("Exited with error code "+exitVal); } catch(Exception e) { System.out.println(e.toString()); e.printStackTrace(); } }
不要使用cd
,并使用字符串数组方法:
rt.exec(new String[]{"C:\\Program Files\\OpenOffice.org 3\\program\\soffice.exe", "-headless", "-accept='socket,host=127.0.0.1,port=8100;urp;'", "-nofirststartwizard"});
最后我解决了它
String[] SOFFICE_CMD = { "C:/Program Files/OpenOffice.org 3/program/soffice", "-accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager", "-invisible", "-nologo"}; Runtime.getRuntime().exec(SOFFICE_CMD);
谢谢大家的支持!!
@Harinder:我想建议一种替代方法。 你能做的是;
-
首先尝试使用所有属性等直接从命令提示符运行您想要运行的任何内容。一旦您从命令提示符处成功运行服务/应用程序,请直接执行2。
-
转到并将命令保存在.bat文件中。
例如:C:\ m-admin \ app.exe我在App上保存了这个app.bat:C:\
- 现在相应地修改你的java代码来执行这个脚本,然后执行你的应用程序或服务。
例如:
ProcessBuilder builder = new ProcessBuilder(new String[]{"cmd", "/c","C:\\app.bat"}); Process pr = builder.start(); BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
- 即使这不起作用……我们需要从头开始。
我使用流程构建器方法编辑了代码(下面)。 看看这是否适合你。 由于访问冲突,使用exec有时不起作用:
public static void main(String[] args) { // TODO Auto-generated method stub try { Runtime rt = Runtime.getRuntime(); //Process pr = rt.exec("cmd /c dir"); // Process pr = rt.exec("cmd /c dir"); ProcessBuilder builder = new ProcessBuilder(new String[]{"cmd", "/c", "C:\\Program Files\\OpenOffice.org 3\\program", "soffice", "-headless", "-accept='socket,host=127.0.0.1,port=8100;urp;'", "-nofirststartwizard"}); Process pr = builder.start(); BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line=null; while((line=input.readLine()) != null) { System.out.println(line); } int exitVal = pr.waitFor(); System.out.println("Exited with error code "+exitVal); } catch(Exception e) { System.out.println(e.toString()); e.printStackTrace(); } }
}
我想我已经找到了你的错误:将你的论点改为以下内容:看看它是否有效:
(new String[]{"cmd", "/c", "C:\\Program Files\\OpenOffice.org 3\\program\\soffice", "-headless", "-accept='socket,host=127.0.0.1,port=8100;urp;'", "-nofirststartwizard"})
退出状态0通常表示没有错误。
请尝试使用ProcssBuilder。
使用ProcessBuilder,您可以设置工作目录 。
以下 是 一些可能有用的链接 。