gpt4 book ai didi

java - 使用 java 执行 shell 命令时与进程通信

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:19:05 25 4
gpt4 key购买 nike

我要从 java 执行一个 shell 命令,我需要在执行命令时将参数传递给输出流。

以下是shell命令

./darknet detect cfg/yolo-voc.2.0.cfg backup/yolo-voc_20000.weights

当执行此命令时,它会生成终端中图像文件的路径,我可以按如下方式提供图像的路径

Loading weights from backup/yolo-voc_21000.weights...Done!
Enter Image Path:

从终端执行时,我可以提供那里的路径。

我设法使用 java 进程执行此命令,并且当我为命令提供图像 uri 时,我也可以获得输出。这是代码

     public static void execCommand(String command) {
try {

Process proc = Runtime.getRuntime().exec(command);
// Read the output
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));

String line = "";
//reader.readLine();
while ((line = reader.readLine()) != null) {
System.out.print(line + "\n");
s.add(line);
}
// proc.waitFor();
} catch (IOException e) {
System.out.println("exception thrown: " + e.getMessage());
}
}

但我想要的是在运行时而不是在命令执行开始时提供图像路径。尝试如下写入输出流仍然没有成功

public static void execCommand(String command) {
try {
Process proc = Runtime.getRuntime().exec(command);
// Read the output
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));

String line = "";
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
writer.append("data/test2.jpg");
writer.newLine();
//reader.readLine();
while ((line = reader.readLine()) != null) {
System.out.print(line + "\n");
s.add(line);
}
// proc.waitFor();
} catch (IOException e) {
System.out.println("exception thrown: " + e.getMessage());
}
}

最佳答案

您需要调用 writer.flush() 才能将某些内容实际输出到下划线 InputStream

因此你的代码应该是这样的:

public static void execCommand(String command) {
try {
Process proc = Runtime.getRuntime().exec(command);

// Read the output
BufferedReader reader = new BufferedReader(new
InputStreamReader(proc.getInputStream()));

String line = "";
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
writer.append("data/test2.jpg");
writer.newLine();
// **** add flush here ****
writer.flush();
// and remember to close your resource too
writer.close();
//reader.readLine();
while ((line = reader.readLine()) != null) {
System.out.print(line + "\n");
s.add(line);
}
// ***** close your reader also ****
reader.close();
// proc.waitFor();
} catch (IOException e) {
System.out.println("exception thrown: " + e.getMessage());
}
}

关于java - 使用 java 执行 shell 命令时与进程通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46294149/

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