I’m trying to write a Java program to run terminal command. Googling and SO got me to here:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Detector { public static void main(String[] args) { String[] cmd = {"ls", "-la"}; try { Process p = Runtime.getRuntime().exec(cmd); BufferedReader reader = new BufferedReader( new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine()) !=null){ System.out.println(line); } p.waitFor(); } catch (IOException | InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
So far, so good. The problem is if I try to run a command like “python -V” via
String[] cmd = {"python", "-V"};
The program will run, but no output is actually printed out. Any ideas?
Advertisement
Answer
The output you see on your command line when running python -V
is actually being printed to standard error. To capture this, you need to use a different InputStream
, such as this:
BufferedReader errorReader = new BufferedReader( new InputStreamReader(p.getErrorStream()));
The rest of your code is fine.