为什么要避免在java中使用Runtime.exec()? [英] Why should avoid using Runtime.exec() in java?

查看:2728
本文介绍了为什么要避免在java中使用Runtime.exec()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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()?

推荐答案

除非你被困在一个古老的JVM上,否则 java.lang.ProcessBuilder 可以更轻松地指定进程,设置其环境,生成它并处理其文件描述符。

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.


此类用于创建操作系统进程。

This class is used to create operating system processes.

每个 ProcessBuilder 实例管理一组进程属性。 start()方法使用这些属性创建一个新的 Process 实例。可以从同一实例重复调用 start()方法,以创建具有相同或相关属性的新子进程。

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中使用Runtime.exec()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆