我正在编写一个库来覆盖WMctrl shell程序。我在调整窗口大小方面有问题:
String command = "wmctrl -r \"Calculator\" -e 0,100,100,500,500";
System.out.println(command);
String output = this.bashCommandExecutor.execute(command);
System.out.println(output);这不起作用-输出变量为空。但是当我将wmctrl -r“计算器”-e 0,100,100,500,500复制粘贴到终端时,它正常工作。
其他命令如"wmctrl -d“和"wmctrl -l”在this.bashCommandExecutor.execute()方法中工作。
此方法如下所示:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BashCommandExecutor
{
String execute(String bashCommand)
{
Process p = null;
try {
p = Runtime.getRuntime().exec(bashCommand);
p.waitFor();
}
catch (InterruptedException | IOException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(p.getInputStream())
);
String line = "";
StringBuilder sb = new StringBuilder();
try {
while ((line = reader.readLine())!= null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}为什么调整大小在命令行中有效,而在Java应用程序中却不起作用?
发布于 2021-10-07 21:19:59
我发现使用ProcessBuilder类而不是Runtime.exec()可以运行您描述的wmctrl命令。因此,与其:
String bashCommand = "wmctrl -r \"Calculator\" -e 0,100,100,500,500";
Process p = Runtime.getRuntime().exec(bashCommand);你可以试试:
String bashCommand = "wmctrl -r \"Calculator\" -e 0,100,100,500,500";
ProcessBuilder pb = new ProcessBuilder("bash", "-c", bashCommand);
Process p = pb.start();Here is a link到另一篇文章,解释Runtime.exec()和使用ProcessBuilder之间的区别。
https://stackoverflow.com/questions/44475990
复制相似问题