gpt4 book ai didi

java - 在浏览器中显示 Sh 脚本输出

转载 作者:行者123 更新时间:2023-11-30 08:23:27 25 4
gpt4 key购买 nike

我有一个 webappliaction(在 Jsp 和 Severlet 中开发),它执行 sh 脚本并仅在执行脚本后在浏览器中显示输出,但我想打印输出,就像它在终端中的执行方式一样(一个一个地执行,例如 ping命令)。这样用户就会有在 unix 终端上工作的体验。我的脚本将运行将近一分钟(脚本开始停止我的 WAS 服务器)所以用户不应该等到一分钟才能看到最终输出。他们应该在启动进程后看到脚本启动输出。请在下面找到我的示例代码。

pb = new ProcessBuilder("/bin/sh",script);
pb.directory(new File(filePath));
p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null){
System.out.println(line);
out.println(line);
}
p.waitFor();
System.out.println ("exit: " + p.exitValue());
out.println("exit: " + p.exitValue());
p.destroy();
out.println("Script Executed");

请任何人指导我。

最佳答案

最后我找到了解决问题的方法,我只是在 out.println(line); 之后添加了 out.flush(),所以它每次都会将输出刷新到浏览器在 while 循环中,它看起来像 unix 终端。下面的代码发挥了作用。

            pb = new ProcessBuilder("/bin/sh",script);
pb.directory(new File(filePath));
p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null){
System.out.println(line);
out.println(line);
out.flush();
}
p.waitFor();
System.out.println ("exit: " + p.exitValue());
out.println("exit: " + p.exitValue());
p.destroy();
out.println("Script Executed");

关于java - 在浏览器中显示 Sh 脚本输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23679898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com