Print Windows cmd output with Java

For some Java applications it might be important to access the console to print some information from a console command. That’s why I wrote a little program which reads the output from the Windows command-line interface (cmd) and shows it on the screen. Note: This script also works on a Linux shell!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class ConsoleOutputPrinter
{
 
  static final Logger logger = Logger.getLogger(ConsoleOutputPrinter.class.getName());
 
  public static String getOutputFromConsoleCommand(String command) throws UnsupportedEncodingException, IOException
  {
    Process console = Runtime.getRuntime().exec(command);
    String consoleEncoding = "UTF-8";
    if (System.getProperty("os.name").contains("Windows"))
      consoleEncoding = "CP850";
 
    InputStream is = console.getInputStream(); // use .getErrorStream() for error messages!
    BufferedReader br = new BufferedReader(new InputStreamReader(is, consoleEncoding));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = br.readLine()) != null)
    {
      sb.append(line).append(System.getProperty("line.separator"));
    }
 
    return sb.toString();
  }
 
  public static void main(String[] args)
  {
    try
    {
      String consoleOutput = getOutputFromConsoleCommand("ping localhost");
      System.out.println(consoleOutput);
    }
    catch (IOException ex)
    {
      logger.log(Level.WARNING, ex.getLocalizedMessage());
    }
  }
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.