用Java获取Cmd输出

时间:2017-04-24 09:09:22

标签: java batch-file cmd

尝试将cmd输出重定向到Java var时出现问题。

我的来源:

System.out.println("Init WAR packaging");
ProcessBuilder builder = new ProcessBuilder(Arrays.asList(new String[] {"cmd.exe", "/C", "start", "/wait", "new.bat"}));
Process process = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder strBuilder = new StringBuilder();
String line = null;
while (process.isAlive()) {
    if((line = reader.readLine()) != null) {
        strBuilder.append(line);
        strBuilder.append(System.getProperty("line.separator"));
    } else {
        System.out.println("123");
        Thread.sleep(10);
    }
}
String result = strBuilder.toString();
System.out.println(result);
System.out.println("Start WAR packaging");

批次主要包含:

jar -cvf test.war *.jsp *.xml

我在控制台中获得的输出:

Init WAR packaging
123

Start WAR packaging

所以我得到的CMD输出为null,实际的CMD输出如下:

asdf.jsp wird hinzugefügt(ein = 17270) (aus = 4693)(72 % verkleinert)
qwer.jsp wird hinzugefügt(ein = 12969) (aus = 3519)(72 % verkleinert)
yxcv.jsp wird hinzugefügt(ein = 22463) (aus = 5375)(76 % verkleinert)
rewq.jsp wird hinzugefügt(ein = 30687) (aus = 6748)(78 % verkleinert)
jhgf.jsp wird hinzugefügt(ein = 47974) (aus = 11005)(77 % verkleinert)

我认为这实际上是它的样子。

非常感谢任何帮助,因为我无法与谷歌/其他stackoverflow问题上的信息相提并论。

谢谢你,祝你有愉快的一天:)

编辑:

我按照arataj的建议修改了整个代码(希望我能帮到你):

ProcessBuilder builder = new ProcessBuilder(Arrays.asList(new String[] {"cmd.exe", "/C", "start", "/wait", "new.bat"}));
        Process process = builder.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder strBuilder = new StringBuilder();
        String line = null;
        while (process.isAlive()) {
            Thread.sleep(10);
            line = reader.readLine();
            strBuilder.append(line);
            strBuilder.append(System.getProperty("line.separator"));
        }
        line = reader.readLine();
        strBuilder.append(line);
        String result = strBuilder.toString();
        System.out.println(result);

控制台输出:

Init WAR packaging
null
null
Start WAR packaging

1 个答案:

答案 0 :(得分:2)

解决了这个问题,问题是我无法访问我想要的输出,因为它是由一个叫另一个comman的命令引起的。

我在代码中解决它的方式:

ProcessBuilder builder = new ProcessBuilder("cmd.exe");
Process  process = builder.start();
BufferedWriter out = new BufferedWriter(new 
OutputStreamWriter(process.getOutputStream()));
InputStream stdout = process.getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));

out.write("start /b new.bat\n");
out.flush();
out.close();

Scanner scanner = new Scanner(stdout);
while (scanner.hasNextLine()) {
    System.out.println(scanner.nextLine());
}
System.out.println("end");
scanner.close();

Awnser基于this

感谢您的帮助!