[英]Bash real time output from java run
I have the following bash script, example.sh that has some lines of code.To reproduce what I need let's say that I have in the script the following lines: 我有以下bash脚本example.sh,其中包含一些代码行。要重现我需要的内容,可以说脚本中有以下几行:
#!/bin/bash
echo First part of program
sleep 3
echo Second part of program
So, when I run this directly from terminal I get the first part printed to the screen(First part of program) then wait 3 seconds and after that I get the next part on the screen(Second part of program). 因此,当我直接从终端运行此程序时,我将第一部分打印到屏幕上(程序的第一部分),然后等待3秒钟,然后我在屏幕上得到第二部分(程序的第二部分)。 When I run this in java, I execute the scipt, wait 3 seconds then I get both parts printed on screen.
当我在Java中运行此代码时,我将执行scipt,等待3秒钟,然后在屏幕上同时打印两个部分。 Is there a way to get the same effect as when running from terminal?
有没有一种方法可以从终端运行时获得相同的效果?
EDIT! 编辑! This is my code:
这是我的代码:
public void executeCommand(String command) {
String line;
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
setOutput(output.toString());
output = new StringBuffer();
BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
line="";
while ((line = error.readLine())!= null) {
output.append(line + "\n");
}
setError(output.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
If you start your script with the Process
-Class then you can fetch the output of the script with for example: 如果使用
Process
-Class启动脚本,则可以使用以下命令获取脚本的输出:
ProcessBuilder pb = new ProcessBuilder("<bashname>", "<scriptpath>");
Process p = pb.start();
OutputStream ops = p.getOutputStream();
There must be the output immediatly. 必须立即有输出。
SOLVED: redirect output and error into files using: 解决:使用以下命令将输出和错误重定向到文件中:
ProcessBuilder builder = new ProcessBuilder("sh",command);
builder.redirectOutput(new File("out.txt"));
builder.redirectError(new File("err.txt"));
try{
Process p = builder.start();
}catch(IOException e){
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.