我使用ProcessBuilder
在我的应用程序Start&Stop Derby Network Server
执行cmd命令。 但有些事情出错了,我不知道问题出在哪里。 让我解释一下。
启动networking服务器;
//Defining path of db files located File file= new File(FirstTimeMainFrame.class.getProtectionDomain() .getCodeSource() .getLocation() .getPath().replace(new File(FirstTimeMainFrame.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName(), "").replace("%20", " ")); String path = file+"\\DB"; //Process Creating ProcessBuilder builder = new ProcessBuilder(); Process process = null; String[] command = new String[3]; command[0] = "cmd.exe"; command[1] = "/c"; //This things say to CMD close when commands complete. command[2] = "cd "+path+" && java -jar derbyrun.jar server start"; builder = new ProcessBuilder(command[0], command[1], command[2]); builder.redirectErrorStream(true); process = builder.start(); //Reading CMD outputs BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while (true) { line = br.readLine(); if (line == null) { break; } System.out.println(line); }
当我debugging项目,我看到输出两行和debugging卡line = br.readLine();
While
循环来检查第三次。 整个程序卡住了,无法继续。
输出;
Fri Dec 25 20:54:36 EET 2015 : Security manager installed using the Basic server security policy. Fri Dec 25 20:54:36 EET 2015 : Apache Derby Network Server - 10.12.1.1 - (1704137) started and ready to accept connections on port 1527
重要的PS:如果我删除//Reading CMD outputs codes
所有的东西完美的工作。 服务器启动,数据库创build,创build表等
我也直接在Windows下尝试相同的CMD命令。 当我执行命令,两行writed和命令提示窗口卡在闪烁的光标(不closures或完整,我认为),但德比服务器启动没有问题在编程或直接在Windows中。
实际上有两个进程正在运行:从Java代码开始的CMD进程和由CMD产生的Derby服务器进程。
Derby服务器进程的输出被定向到命令行,然后可以用java代码读取。 服务器进程可以长时间运行直到它将被终止,这就是为什么输出流永远不会结束。
挂在Java代码发生,因为目前在流中没有可用的字节 – 服务器进程告诉你,它已成功初始化,然后转移到等待状态。