How do I use Linux commands in my Java classes (e.g. ppp dialup scripts)?

Nathan Meyers

You can use the Runtime.exec() methods to execute commands. For example:


Some methods take an array of arguments, others take command strings which are subsequently split up into an array of arguments. If you want to interpret shell metacharacters (such as redirection characters and pipes) in your command, you'll need to run a shell and pass the command to it for interpretation:

  Runtime.getRuntime().exec(new String[] { "sh", "-c", "ls >foo" })

Whichever method you use, you'll need to open file descriptors on the Process object returned from exec() to send it input or obtain its output:

  Process process = Runtime.getRuntime().exec("...command...");
  InputStream input = process.getInputStream();