how to excute a linux shell command in java

quoted from: http://bbs.chinaunix.net/viewthread.php?tid=841011&extra=page%3D4

/* test.java */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class test
{
    public static void main(String[] args)
    {
        String lsString = null;
        Process process = null;
        try
        {
            process = Runtime.getRuntime().exec(“ls”);
            BufferedReader bufferedReader = new
                BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((lsString = bufferedReader.readLine()) != null)
            {
                System.out.println(lsString);
            }
            try
            {
                process.waitFor();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
} // end test.java

Advertisement

10 Responses to “how to excute a linux shell command in java”

  1. thanks a lot, it is what I was looking for…

  2. Thanks, chears!

  3. Exactly what i needed !
    Thanks a lot

  4. Nitin Gautam Says:

    What if you are on Window and want to connect using Java to Linux server and then run some command on it?

  5. if i want to adduser how to it?
    since it needs root authentification

  6. hello i was trying to compile and execute files like .cpp and .java when i compiling was fine
    but when i was trying to execute it i do nothing can someone help me with this

    String command_compile=”javac print.java”;
    String command_run=”java Main out.out”;

    try {
    final Process pro= Runtime.getRuntime().exec(command_compile);
    final Process p=Runtime.getRuntime().exec(command_run);
    } catch (Exception e) {
    System.out.println(e.getClass());
    }

  7. sorry the variable command_run is like this
    String command_run=”java Main out.out”;

  8. atrakcje eventy łódź…

    [...]how to excute a linux shell command in java « Home[...]…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.