Advertisement
DulcetAirman

Java and WSL

Jun 11th, 2019
552
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.01 KB | None | 0 0
  1. package ch.claude_martin.foo;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.nio.charset.Charset;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9.  
  10. public class SomeClass {
  11.  
  12.     public static void main(String[] args) throws InterruptedException {
  13.         try {
  14.             // The old CMD on Windows uses UTF-16:
  15.             var utf16 = Charset.forName("UTF-16LE");
  16.             System.out.println(execute("cmd /U /C echo hello", utf16));
  17.            
  18.             // Linux usually has UTF-8 as the default encoding:
  19.             var utf8 = Charset.forName("UTF-8");
  20.             // using WSL we can easily access the Linux subsystem:
  21.             System.out.println(execute("wsl echo hello", utf8));
  22.             // You get a List. Use .get(0) to get the first line:
  23.             System.out.println(execute("wsl uname -a", utf8).get(0));
  24.             // This only works when Windows is installed on C:\
  25.             System.out.println(execute("wsl ls /mnt/c/Users", utf8));
  26.             // But you can combine CMD and WSL to make sure you get the correct paths:
  27.             var home = execute("cmd /U /C echo %USERPROFILE%", utf16).get(0);
  28.             System.out.println(execute(String.format("wsl wslpath '%s'", home), utf8));
  29.         } catch (IOException e) {
  30.             e.printStackTrace();
  31.         }
  32.     }
  33.  
  34.     /**
  35.      * Run given command and return the data read from stdout.
  36.      *
  37.      * @param cmd the command, for example "cmd /U /C echo foo"
  38.      * @return The output of the command as a List of Strings.
  39.      * @throws IOException Thrown when executing the command or reading the data
  40.      *                     fails.
  41.      */
  42.     public static List<String> execute(final String cmd, Charset encoding) throws IOException {
  43.         Process p = null;
  44.         try {
  45.             p = Runtime.getRuntime().exec(cmd);
  46.             try (var br = new BufferedReader(new InputStreamReader(p.getInputStream(), encoding))) {
  47.                 List<String> result = new ArrayList<>();
  48.                 for (;;) {
  49.                     String line = br.readLine();
  50.                     if (line == null)
  51.                         break;
  52.                     result.add(line);
  53.                 }
  54.                 return result;
  55.             }
  56.         } finally {
  57.             if (p != null)
  58.                 p.destroy();
  59.         }
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement