gpt4 book ai didi

java - 为什么要避免在 java 中使用 Runtime.exec()?

转载 作者:搜寻专家 更新时间:2023-10-30 19:49:59 25 4
gpt4 key购买 nike

   Process p = Runtime.getRuntime().exec(command);
is = p.getInputStream();
byte[] userbytes = new byte[1024];
is.read(userbytes);

我想在 linux 操作系统中从 java 执行 shell 命令。但是 pmd 报告说不要使用 java Runtime.exec()。为什么?是什么原因 ? Runtime.exec() 有其他替代方法吗?

最佳答案

除非你被困在一个古老的 JVM 上,java.lang.ProcessBuilder使得指定进程、设置其环境、生成它以及处理其文件描述符变得更加容易。

This class is used to create operating system processes.

Each ProcessBuilder instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes. The start() method can be invoked repeatedly from the same instance to create new subprocesses with identical or related attributes.

...

Starting a new process which uses the default working directory and environment is easy:

 Process p = new ProcessBuilder("myCommand", "myArg").start();

Here is an example that starts a process with a modified working directory and environment:

 ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory(new File("myDir"));
Process p = pb.start();

关于java - 为什么要避免在 java 中使用 Runtime.exec()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10723346/

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