1,105,242 Community Members

Running console command from within Java

Member Avatar
Newbie Poster
10 posts since Oct 2007
Reputation Points: -2 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]

I am using the following string and Java code to create a user on a Linux box via Java.

String x = "/usr/sbin/useradd -g users -s /bin/bash -c 'FIRST M LAST,  STERK,DIV-DIS-OFF,123-456-2913' -p 2342asdfa231rcawef09  -d /home/flast -m flast";


However, upon execution it spins a list of the usage of useradd... It has something to do with the spaces in the comment field I think. Anyone have any insight as to a solution to this problem?

public static String RunCommand (String cmd)
        String s = null;
        String results = null;
        try {
        // run the Unix "ps -ef" command
            // using the Runtime exec method:
            // Process p = Runtime.getRuntime().exec("ps -ef");
            Runtime rt = Runtime.getRuntime();
            Process p = rt.exec(cmd);

            BufferedReader stdInput = new BufferedReader(new
            BufferedReader stdError = new BufferedReader(new
            // read the output from the command
            //System.out.println("Here is the standard output of the command:\n");
            while ((s = stdInput.readLine()) != null)
                results = results + s;
            // read any errors from the attempted command
            //System.out.println("Here is the standard error of the command (if any):\n");
            while ((s = stdError.readLine()) != null)
                results = results + s;
            return results.toString();
        catch (IOException e)
            System.out.println("[RunCommand] - ERROR: " + e.getMessage());
            return e.getMessage();
Member Avatar
Industrious Poster
4,165 posts since Feb 2006
Reputation Points: 1,351 [?]
Q&As Helped to Solve: 510 [?]
Skill Endorsements: 22 [?]
Team Colleague

Use the array version of the exec method. See the API docs.

Member Avatar
Practically a Posting Shark
809 posts since Feb 2007
Reputation Points: 193 [?]
Q&As Helped to Solve: 77 [?]
Skill Endorsements: 0 [?]

Don't forget to close the streams.

This article has been dead for over three months: Start a new discussion instead
Start New Discussion
View similar articles that have also been tagged: