Elevating a ProcessBuilder process via UAC?

This can’t be done with ProcessBuilder, you will need to call Windows API. I’ve used JNA to achieve this with code similar to the following: Shell32X.java: import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.WString; import com.sun.jna.platform.win32.Shell32; import com.sun.jna.platform.win32.WinDef.HINSTANCE; import com.sun.jna.platform.win32.WinDef.HWND; import com.sun.jna.platform.win32.WinNT.HANDLE; import com.sun.jna.platform.win32.WinReg.HKEY; import com.sun.jna.win32.W32APIOptions; public interface Shell32X extends Shell32 { Shell32X INSTANCE = … Read more

How to redirect ProcessBuilder’s output to a string?

Read from the InputStream. You can append the output to a StringBuilder: BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuilder builder = new StringBuilder(); String line = null; while ( (line = reader.readLine()) != null) { builder.append(line); builder.append(System.getProperty(“line.separator”)); } String result = builder.toString();

How to set working directory with ProcessBuilder

You are trying to execute /home and it is not an executable file. The constructor argument of the process builder is the command to execute. You want to set the working directory. You can that it via the directory method. Here is a complete example: Process p = null; ProcessBuilder pb = new ProcessBuilder(“do_foo.sh”); pb.directory(new … Read more

Executing another application from Java

The Runtime.getRuntime().exec() approach is quite troublesome, as you’ll find out shortly. Take a look at the Apache Commons Exec project. It abstracts you way of a lot of the common problems associated with using the Runtime.getRuntime().exec() and ProcessBuilder API. It’s as simple as: String line = “myCommand.exe”; CommandLine commandLine = CommandLine.parse(line); DefaultExecutor executor = new … Read more

ProcessBuilder: Forwarding stdout and stderr of started processes without blocking the main thread

Use ProcessBuilder.inheritIO, it sets the source and destination for subprocess standard I/O to be the same as those of the current Java process. Process p = new ProcessBuilder().inheritIO().command(“command1”).start(); If Java 7 is not an option public static void main(String[] args) throws Exception { Process p = Runtime.getRuntime().exec(“cmd /c dir”); inheritIO(p.getInputStream(), System.out); inheritIO(p.getErrorStream(), System.err); } private … Read more

tech