Save cmd command result executed from java in a variable

4

Is it possible to store the result of the execution of a command from java in a variable of type string? I've tried it this way but the output of stdInput.readLine () is always NULL, something I'm doing wrong. Another question is whether it is possible to concatenate the result of the execution of the command1 as I am doing in command2, by entering the variable in the middle of the string of the command? The code is as follows:

    public class PDOFinder{

    //PdoFinder constructor
    public PDOFinder(){
    }

    //variables to store device data
    static String webcamPDOName = null;
    static String webcamDeviceID = null;

    public static void main(String[] args) throws IOException{

        try{

            String output = null;
            String output2 = null;

            String[] command = new String[3];
            command[0] = "cmd.exe";
            command[1] = "/c";
            command[2] = "C:\Users\user1\Desktop\devcon.exe find =image | findstr USB\VID*";

            Process process1 = Runtime.getRuntime().exec(command);

            InputStreamReader input = new InputStreamReader(process1.getInputStream());
            BufferedReader stdInput = new BufferedReader(input);

            System.out.println("salidaaa: "+stdInput.readLine());

            if((output=stdInput.readLine()) != null){
                webcamDeviceID = stdInput.readLine();
            }

            System.out.println(webcamDeviceID);

            String[] command2 = new String[3];
            command2[0] = "cmd.exe";
            command2[1] = "/c";
            command2[2] = "wmic path Win32_PnPSignedDriver where 'deviceid="+webcamDeviceID+"' get pdo";

            Process process2 = Runtime.getRuntime().exec(command2);
            InputStreamReader input2 = new InputStreamReader(process2.getInputStream());
            BufferedReader stdInput2 = new BufferedReader(input2);

            if((output2=stdInput2.readLine()) != null){
                webcamPDOName = stdInput2.readLine();
            }

            System.out.println(webcamPDOName);
        }
        catch(Exception e){
            System.out.println("Exception: "+e);
            e.printStackTrace();
        }
    }
}
    
asked by Tofetopo 26.01.2017 в 19:31
source

2 answers

1

Using ProcessBuilder you can put stdout and stderr of your process. The waitFor() method blocks execution and waits until the process ends, then returning the result (normally 0 in case of normal termination or> = 1 in case of error).

You can use this class to simplify your life:

/**
 * @author snolde
 *
 */
public class ProcToString {


    private ProcessBuilder pb;
    private String out=null;
    private Process proc=null;

    public ProcToString(String... cmd){
        pb = new ProcessBuilder(cmd);
        // redirigir stdErr>stdOut
        pb.redirectErrorStream(true);
    }

    // espera a que el proceso termina y devuelve el estado
    public int runProcess() throws IOException, InterruptedException{
        proc = pb.start();
        new Stream().start();
        return proc.waitFor();
    }

    // el proceso tiene resultado?
    public boolean hasResult(){
        return !proc.isAlive() && out!=null;
    }

    //devuelve resultado o null
    public String getResult(){
        return out;
    }

    final class Stream extends Thread{

        @Override
        public void run() {
            StringBuilder sb=new StringBuilder();
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            try {
                while((line = br.readLine())!=null){
                    sb.append(line).append("\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                out=sb.toString();
            }
        }
    }

}

you can use it in this way:

        ProcToString pts=new ProcToString("cmd.exe", "/C", "dir");
        try {
            System.out.println(pts.runProcess());
            if (pts.hasResult()){
                // aquí viene tu resultado
                String resultado = pts.getResult();
                System.out.println(resultado);
            }
        } catch (IOException | InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
answered by 26.01.2017 в 22:44
0

Change getInputStream by getErrorStream in this way:

InputStreamReader input = new InputStreamReader(process1.getErrorStream());

If it returns a correct value, if you can concatenate it in the next command.

    
answered by 26.01.2017 в 20:57