有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

为什么应该避免使用运行时。java中的exec()?

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

我想从java在linux操作系统中执行一个shell命令。但是pmd报告说不要使用java运行时。exec()。为什么?原因是什么?运行时是否有其他选择。exec()


共 (1) 个答案

  1. # 1 楼答案

    除非您停留在一个古老的JVM上,^{}使指定进程、设置其环境、生成它以及处理其文件描述符变得更加容易

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