为什么要避免在 Java 中使用 Runtime.exec()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10723346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why should avoid using Runtime.exec() in java?
提问by kannanrbk
Process p = Runtime.getRuntime().exec(command);
is = p.getInputStream();
byte[] userbytes = new byte[1024];
is.read(userbytes);
I want to execute a shell command in linux os from java . But pmd reports says don't use java Runtime.exec(). Why? What is the reason ? Is there any alternative for Runtime.exec()?
我想在 linux os 中从 java 执行一个 shell 命令。但是 pmd 报告说不要使用 java Runtime.exec()。为什么?是什么原因 ?Runtime.exec() 有什么替代方法吗?
回答by Mike Samuel
Unless you're stuck on an ancient JVM, java.lang.ProcessBuilder
makes it much easier to specify a process, set up its environment, spawn it, and handle its file descriptors.
除非您坚持使用古老的 JVM,java.lang.ProcessBuilder
否则可以更轻松地指定进程、设置其环境、生成它并处理其文件描述符。
This class is used to create operating system processes.
Each
ProcessBuilder
instance manages a collection of process attributes. Thestart()
method creates a newProcess
instance with those attributes. Thestart()
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();
此类用于创建操作系统进程。
每个
ProcessBuilder
实例管理一组流程属性。该start()
方法Process
使用这些属性创建一个新实例。start()
可以从同一实例重复调用该方法以创建具有相同或相关属性的新子流程。...
启动一个使用默认工作目录和环境的新进程很容易:
Process p = new ProcessBuilder("myCommand", "myArg").start();
这是一个使用修改后的工作目录和环境启动进程的示例:
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();