2

Created this function to input unix commands and output the outputs of that unix command. But, I am having trouble with the unix commands I use. "ls" works to output the list of files, but if I do "ls -lart" it will output null. Having trouble further debugging or why this doesn't work. Code below.

private String[] unixCommand (String command, Boolean boolOutput) throws IOException, InterruptedException{
    Process run;
    int i = 0;
    String output = "";
    String[] finalOutput = new String[1000];
    sendToProcessView("Unix Command: " + command);
    run = Runtime.getRuntime().exec(command);
    run.waitFor();
    sendToProcessView("In Unix Command");
    if (boolOutput == true){        
        sendToProcessView("In Output Mode of Unix Command");
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(run.getInputStream()));
        sendToProcessView("Passed Buffer Reader");
        while ((output = stdInput.readLine()) != null) {
            sendToProcessView("Output: " + output);
            finalOutput[i] = output;
            i++;
        }
    }
    return finalOutput;
}
3
  • Call run.waitFor() after you have consumed the command’s output, not before. Commented Jun 13, 2016 at 19:45
  • Found out that it will accept " ls " commands but wont take " ls Main* " commands with wildcard. Commented Jun 14, 2016 at 14:46
  • Runtime.getRuntime().exec(new String[] { "bash", "-c", myCommand }); Commented Jun 14, 2016 at 14:56

1 Answer 1

1

When interacting with the console, you should exec the console itself, and then use the Process input stream to send commands, eg (pseudocode - I'm not set up to test java code from my location, sorry)

sendToProcessView("Unix Command: " + command);
run = Runtime.getRuntime().exec("bash");
PrintStream in = new PrintStream(run.getOutputStream());
in.println("ls -lart");

You can then shut the process down by sending "exit" and reading the results the way you were, or using a threaded listener, like DataFetcher

Sign up to request clarification or add additional context in comments.

3 Comments

PrintStream gave a constructor error and yea I agree that exiting the process is best practice, but did not fix the null issue.
I have fixed the code snippet - it is now run.getOutputStream() (was getInputStream())
Sorry but not printing it out to the terminal. Returning the value back from the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.