在Java中执行Linux命令,日志都是在命令执行完返回,现在用zt-exec实现日志实时同步输出
第一步:maven中引用zt-exec
<dependency>
<groupId>org.zeroturnaround</groupId>
<artifactId>zt-exec</artifactId>
<version>1.11</version>
</dependency>
第二步:编写工具类并测试
import com.yeexun.webgl.config.websocket.WebSocketServer;
import org.zeroturnaround.exec.ProcessExecutor;
import org.zeroturnaround.exec.stream.LogOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeoutException;
/**
* @Author 小伍子安
* @Date 2020/8/5 16:33
* @Version 1.0
*/
public class ZtExecCommandServer {
public static Integer exec(String sid,String... command) throws InterruptedException, TimeoutException, IOException {
int exit = new ProcessExecutor().command(command).destroyOnExit().redirectOutput(new LogOutputStream() {
@Override
protected void processLine(String s) {
System.out.println("成功日志:"+s);
try {
WebSocketServer.sendInfo("<span style='color:green;'>"+s+"</span>",sid);
} catch (IOException e) {
e.printStackTrace();
}
}
}).redirectError(new LogOutputStream() {
@Override
protected void processLine(String s) {
System.out.println("错误日志:"+s);
try {
WebSocketServer.sendInfo("<span style='color:red;'>"+s+"</span>",sid);
} catch (IOException e) {
e.printStackTrace();
}
}
}).execute().getExitValue();
return exit;
}
public static void main(String[] args) throws InterruptedException, IOException, TimeoutException {
exec(UUID.randomUUID().toString(),"ping","www.baidu.com");
}
}
zt-exec源码地址:zt-exec.