[英]Executing command line, cd doesn't work
I'm trying to execute cd
using我正在尝试使用执行
cd
try {
Process process = Runtime.getRuntime().exec(command);
BufferedReader stream = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = stream.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append('\n');
}
stream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = stream.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append('\n');
}
} catch (IOException e) {
e.printStackTrace();
}
ls
works. ls
有效。 But cd dir
doesn't work.但是
cd dir
不起作用。 It doesn't change the directory.它不会更改目录。 If I execute
pwd
, it still shows /
.如果我执行
pwd
,它仍然显示/
。 I read that each time Runtime.getRuntime().exec(command);
我每次都读到
Runtime.getRuntime().exec(command);
is executed, it creates a new shell.被执行,它会创建一个新的shell。 I think I need to capture that shell some how and maintain it till the user closes the app.
我想我需要以某种方式捕获该外壳并对其进行维护,直到用户关闭该应用程序。
Not just that, I'm not getting any errors in my output.不仅如此,我的输出中没有任何错误。 Eg.
例如。 when I put a command that does not exist, I don't get the error message.
当我输入一个不存在的命令时,我没有收到错误消息。
I read that each time Runtime.getRuntime().exec(command);
我每次都读到 Runtime.getRuntime().exec(command); is executed, it creates a new shell.
被执行,它会创建一个新的shell。
That is correct.那是正确的。 When you call
Runtime.exec()
for each command, you are creating a new process.当您为每个命令调用
Runtime.exec()
,您正在创建一个新进程。 Each process gets its own environment, including a separate working directory which does not affect the parent process (your app), or any other processes you create afterwards.每个进程都有自己的环境,包括一个单独的工作目录,它不会影响父进程(您的应用程序)或您之后创建的任何其他进程。
I'm not getting any errors in my output
我的输出中没有任何错误
You don't get any errors because the shell commands do not fail to execute.您不会收到任何错误,因为 shell 命令不会执行失败。 The commands simply return a status code indicating success or failure when the process terminates - the code can be obtained via
Process.exitValue()
- but make sure the process has finished first using Process.waitFor()
.这些命令只是在进程终止时返回一个指示成功或失败的状态代码 - 该代码可以通过
Process.exitValue()
获得 - 但确保进程首先使用Process.waitFor()
。
If you want to execute multiple commands, you could use exec()
to launch a shell executable and then write commands and read replies via the input and output streams, or just join all the commands together using semicolons and execute them directly using a command line like:如果你想执行多个命令,你可以使用
exec()
来启动一个 shell 可执行文件,然后通过输入和输出流写入命令和读取回复,或者只是使用分号将所有命令连接在一起并使用命令行直接执行它们喜欢:
sh -c 'cd /;pwd'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.