gpt4 book ai didi

java - Runtime.getRuntime().exec ("ls"没有输出)

转载 作者:太空宇宙 更新时间:2023-11-04 15:14:09 27 4
gpt4 key购买 nike

ping 和 date 返回输出,但它没有从“ls”或“pwd”返回任何内容。我最终想做的是运行 SSH 命令。知道我下面缺少什么吗?

//Works and shows the output
executeCommand("ping -c 3 " + "google.com");

//Works and shows the output
executeCommand("date");

//Does not work. No output
executeCommand("sudo ls");

//Does not work. No output
executeCommand("ls");


private void executeCommand(String command) {

StringBuffer output = new StringBuffer();

Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));

String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}

} catch (Exception e) {
e.printStackTrace();
}

Log.d("Output", "Output: " + output.toString());


}

最佳答案

我有两个解决方案

第一个解决方案(您需要 Java 7):

...
ProcessBuilder pb = new ProcessBuilder("ls");
pb.redirectOutput(Redirect.INHERIT);
Process p = pb.start();

第二种解决方案:

    Process p=Runtime.getRuntime().exec("ls");

InputStream is = p.getInputStream();
int c;
StringBuilder commandResponse = new StringBuilder();

while( (c = is.read()) != -1) {
commandResponse.append((char)c);
}
System.out.println(commandResponse);
is.close();

关于java - Runtime.getRuntime().exec ("ls"没有输出),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21035043/

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