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).
You find the code is on pastebin: