With Windows Subsystem for Linux (WSL) we can now use Linux tools, such as grep, rsync, ssh, and network commands, such as dig and netstat, on Windows directly. No need for cygwin or other 3rd party software.
Here’s an example on how uname is unknown to Windows, but WSL (Ubuntu in my case) knows it:

So when writing Java programs you might want to use this feature. There really isn’t much to say about this because youcan just easily use it. But note that WSL probably uses UTF-8 (as most linux systems are using UTF-8) while CMD /U uses UTF-16LE .
I assume you will need 64bit Java. There’s probably a way to run WSL (which is 64bit) from a 32bit executable. But it’s 2019 and I see no reason to run 32bit Java.
Often you run a simple command that returns a single line, such as which or uname. So my function returns a List of Strings, so you can easily get the first line:
System.out.println(execute("wsl uname -a", utf8).get(0));
There’s nothing really special to do. Just use Runtime.getRuntime().exec(cmd) and read from the InputStream (stdout of the process).
package ch.claude_martin.foo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class SomeClass {
public static void main(String[] args) throws InterruptedException {
try {
// The old CMD on Windows uses UTF-16:
var utf16 = Charset.forName("UTF-16LE");
System.out.println(execute("cmd /U /C echo hello", utf16));
// Linux usually has UTF-8 as the default encoding:
var utf8 = Charset.forName("UTF-8");
// using WSL we can easily access the Linux subsystem:
System.out.println(execute("wsl echo hello", utf8));
// You get a List. Use .get(0) to get the first line:
System.out.println(execute("wsl uname -a", utf8).get(0));
// This only works when Windows is installed on C:\
System.out.println(execute("wsl ls /mnt/c/Users", utf8));
// But you can combine CMD and WSL to make sure you get the correct paths:
var home = execute("cmd /U /C echo %USERPROFILE%", utf16).get(0);
System.out.println(execute(String.format("wsl wslpath '%s'", home), utf8));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Run given command and return the data read from stdout.
*
* @param cmd the command, for example "cmd /U /C echo foo"
* @return The output of the command as a List of Strings.
* @throws IOException Thrown when executing the command or reading the data
* fails.
*/
public static List<String> execute(final String cmd, Charset encoding) throws IOException {
Process p = null;
try {
p = Runtime.getRuntime().exec(cmd);
try (var br = new BufferedReader(new InputStreamReader(p.getInputStream(), encoding))) {
List<String> result = new ArrayList<>();
for (;;) {
String line = br.readLine();
if (line == null)
break;
result.add(line);
}
return result;
}
} finally {
if (p != null)
p.destroy();
}
}
}
You find the code is on pastebin: