英文:
How to run an infinite Stream until an argument and then collect said Stream into a String?
问题
我想运行类似于 kubectl logs aggregator --namespace load-test --follow
这样的 command
,它是一个流,并且打印出流中的所有输出,直到流中出现特定的 argument
。
public class Command {
String collect;
public void execute(String command, String argument) throws IOException {
final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows");
String[] cmd;
Process process;
// 使命令在Windows或Linux上生效
// 这假设诸如 kubectl 或 minikube 等程序位于 PATH 中
if (IS_WINDOWS) {
cmd = new String[]{"cmd.exe", "/c", command};
} else {
cmd = new String[]{"/bin/bash", "-c", command};
}
// 创建 ProcessBuilder
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
// 启动进程
process = pb.start();
InputStream stdin = process.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
Stream<String> ss = br.lines();
Stream<String> ss2 = br.lines();
// 运行,比如说,实时日志流捕获器,直到它遇到 argument
boolean anyMatch = ss.anyMatch((value) -> value.contains(argument));
// 如果它确实遇到了 argument,将输出收集到字符串中
if (anyMatch) {
collect = ss2.collect(Collectors.joining("\n"));
}
// 清理
process.destroy();
}
public String returnAsString() {
return collect;
}
}
我在创建两个流(例如,使用 streamSupplier
),或者两个 BufferedReader
上遇到了问题,也找不到实现我尝试达到的目标的可行方法。我应该如何做呢?
英文:
I want to run a command
such as kubectl logs aggregator --namespace load-test --follow
, which is a stream, and print all of its output until a certain argument
comes in the stream.
public class Command {
String collect;
public void execute(String command, String argument) throws IOException {
final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows");
String[] cmd;
Process process;
// Make the command work on Windows or Linux
// This assumes programs like kubectl or minikube are in PATH
if (IS_WINDOWS) {
cmd = new String[]{"cmd.exe", "/c", command};
} else {
cmd = new String[]{"/bin/bash", "- c", command};
}
// Create the ProcessBuilder
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
// Start the process
process = pb.start();
InputStream stdin = process.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
Stream<String> ss = Stream.of(br.readLine());
Stream<String> ss2 = Stream.of(br.readLine());
// Run, say, the live log stream catcher, until it hits the argument
boolean anyMatch = ss.anyMatch((value) -> value.contains(argument));
// If it did hit the argument, collect the output into the String
if (anyMatch) {
collect = ss2.collect(Collectors.joining("\n"));
}
// Clean-up
process.destroy();
}
public String returnAsString() {
return collect;
}
I'm having trouble with creating two streams (e.g., with streamSupplier
) or two BufferedReaders
, or finding any workable way for what I'm trying to achieve. How can I do it?
专注分享java语言的经验与见解,让所有开发者获益!
评论