Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should avoid using Runtime.exec() in java?

Tags:

java

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

like image 955
kannanrbk Avatar asked May 23 '12 15:05

kannanrbk


People also ask

What is the use of runtime in Java?

In Java, the Runtime class is used to interact with Every Java application that has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime () method.

How to get the current runtime in Java?

The current runtime can be obtained from the getRuntime method. Methods of Java Runtime class : 1) public static Runtime getRuntime () : This method returns the instance or Runtime object associated with the current Java application.

What is halt method in runtime getruntime?

Runtime.getRuntime ().halt () The Runtime class allows an application to interact with the environment in which the application is running. It has a halt method that can be used to forcibly terminate the running JVM. Unlike the exit method, this method does not trigger the JVM shutdown sequence.

What is the difference between system exit () and runtime getruntime ()?

As we've seen earlier, the System.exit () method triggers the shutdown sequence of JVM, whereas the Runtime.getRuntime ().halt () terminates the JVM abruptly. We can also do this by using operating system commands.


1 Answers

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.

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();
like image 100
Mike Samuel Avatar answered Oct 12 '22 23:10

Mike Samuel