How to execute a shell command?

What class and method should I use to set an environment variable on a local system? And how do I execute a shell command in Java?
Thanks!

I don't know about setting environment variables from java, but I do know how to execute system commands (and from there you could modify environment variables).
Use Runtime.getRuntime().exec()
There are quite a few pitfalls with using this though...
1. It's platform dependent
2. Doing this creates a Process. If this process has output, you need to read this, otherwise the output buffer will overflow, and that would be bad... Input is not so bad (either supplying it or not ;)
3. If you use Win for example, and want to do a "dir", there are complications, as there is no dir.exe file, and hence it can't be executed... Do a search for this topic, there's plenty on how to get around it.
Anyway, there's plenty more info on Runtime.getRuntime().exec(), have a look around.
Cheers,
Radish21

Similar Messages

  • How to execute a shell command in java?

    here, my environment is redhat 7, jdk 1.5.
    i don't know how to use the shell command in java.
    i want to use this function:
    #include <stdlib.h>
    int system(const char * string);
    please give me some ideas. and Thank you so much if coming with a little demo.

    i know i should use JNI. because i have to use C lib.
    but i have already use JNI to wrapper the original code the cpp code and java code is :
    //: appendixb:UseObjImpl.cpp
    //# Tested with VC++ & BC++. Include path must
    //# be adjusted to find the JNI headers. See
    //# the makefile for this chapter (in the
    //# downloadable source code) for an example.
    #include <jni.h>
    #include <stdlib.h>
    extern "C" JNIEXPORT void JNICALL
    Java_UseObjects_changeObject(
    JNIEnv* env, jobject, jobject obj) {
    jclass cls = env->GetObjectClass(obj);
    jfieldID fid = env->GetFieldID(
    cls, "aValue", "I");
    jmethodID mid = env->GetMethodID(
    cls, "divByTwo", "()V");
    int value = env->GetIntField(obj, fid);
    printf("Native: %d\n", value);
    env->SetIntField(obj, fid, 6);
    env->CallVoidMethod(obj, mid);
    value = env->GetIntField(obj, fid);
    system("preprocess -path sha.c");
    printf("Native: %d\n", value);
    } ///:~
    //: appendixb:UseObjects.java
    // From 'Thinking in Java, 2nd ed.' by Bruce Eckel
    // www.BruceEckel.com. See copyright notice in CopyRight.txt.
    class MyJavaClass {
    public int aValue;
    public void divByTwo() { aValue /= 2; }
    public class UseObjects {
    private native void
    changeObject(MyJavaClass obj);
    static {
    // System.loadLibrary("UseObjImpl");
    // Linux hack, if you can't get your library
    // path set in your environment:
    System.load(
    "/root/jproj/UseObjImpl.so");
    public static void main(String[] args) {
    UseObjects app = new UseObjects();
    MyJavaClass anObj = new MyJavaClass();
    anObj.aValue = 2;
    app.changeObject(anObj);
    System.out.println("Java: " + anObj.aValue);
    } ///:~
    i modify this two file which is from TIJ-2edition.
    the output is
    Native: 2
    Native: 3
    Java: 3
    but what i want to be executed "preprocess -path sha.c" does not work.
    i have change the command to, such as "df", "ls" etc. but none of them works
    please help me.

  • How to Execute Power Shell Command From Windows Application.

    Hi All Experts,
    I want to execute power shell commands from my windows application.
    Is it possible ?
    Please let me know your comments..
    Thanks.

    I have not tried this, but apprently it is easy as in the sample pasted below. please see this article for more details
    http://geekswithblogs.net/Norgean/archive/2012/09/19/running-powershell-from-within-sharepoint.aspx.
    Let me know how it goes...
    public string RunPowershell(string powershellText, SPWeb web, string param1, string param2) {
    // Powershell ~= RunspaceFactory - i.e. Create a powershell context
    var runspace = RunspaceFactory.CreateRunspace();
    var resultString = new StringBuilder();
    try
    // load the SharePoint snapin - Note: you cannot do this in the script itself (i.e. add-pssnapin etc does not work)
    PSSnapInException snapInError;
    runspace.RunspaceConfiguration.AddPSSnapIn("Microsoft.SharePoint.PowerShell", out snapInError);
    runspace.Open();
    // set a web variable.
    runspace.SessionStateProxy.SetVariable("webContext", web);
    // and some user defined parameters
    runspace.SessionStateProxy.SetVariable("param1", param1);
    runspace.SessionStateProxy.SetVariable("param2", param2);
    var pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(powershellText);
    // add a "return" variable
    pipeline.Commands.Add("Out-String");
    // execute!
    var results = pipeline.Invoke();
    // convert the script result into a single string
    foreach (PSObject obj in results)
    resultString.AppendLine(obj.ToString());
    finally
    // close the runspace
    runspace.Close();
    // consider logging the result. Or something.
    return resultString.ToString();
    Ok. We've written some code. Let us test it.
    var runner = new PowershellRunner();
    runner.RunPowershellScript(@"
    $web = Get-SPWeb 'http://server/web' # or $webContext
    $web.Title = $param1
    $web.Update()
    $web.Dispose()
    ", null, "New title", "not used");
    -Sangeetha

  • How to execute unix shell script in webdynpro?

    hi all,
      We have some iquirement of executing script in unix.If anyone know How to execute unix shell script in webdynpro?
    best regard
    reefish

    Ree,
    1. Find SSH client for windows, then execute SSH with Runtime.exec() on local host with arguments like remote host, auth, command to execute etc.
    2. Get SSH client in Java and execute SSH commands on remote host using pure Java API.
    Don't ask me for links, Google works today, I checked this
    Valery Silaev
    SaM Solutions
    http://www.sam-solutions.net

  • Executing a shell command

    Hi,
    I'm new hier and have a short question. How do I execute a shell command from Java code?
    Have a nice day and lot of fun
    Yury

    Search the forum. This is explained well in other threads

  • How to execute unix shell script from Java ...

    Hi,
    Anyone know how to execute unix shell script from Java?
    Suppose I have several shell scripts written in perl or tcl or bash.
    I just want to catch the output of that script.
    Is there any ready to use module/object for this?
    Please let me know, this is quite urgent for my study assigment.
    Thanks in advance,
    Regards,
    me

    Look up Runtime.exec()

  • How to execute a system command with call executable in teststand 4.2.1?

    Hi All,
          how to execute a system command with "call executable" step in teststand 4.2.1?
          example as i want to quit a application.using "taskkill /f /im xxx.exe".And execute other system command(DOS).
    BR
    Johnny

    Hi, 
    I want to run netstat -an | find "8080" command from command prompt using call executable in test stand. after that i would like take the std output to local variable. 
    Attachments:
    callsettings.jpg ‏404 KB

  • How to execute dir dos command in Runtime Execution

    Hi All,
    Does anybody know how to execute the dir command in DOS in the runtime execution
    for example,
    when we open the command prompt,
    c:\Documents and Settings\java> e:
    e:\cd java
    e:\dir *.*
    how we can list the directory in runtime execution?

    Process childProcess = Runtime.getRuntime().exec("cmd /C dir *.*");or try with
    ProcessBuilder pb = new ProcessBuilder("cmd /C dir *.*");
    Process childProcess = pb.start();
    NOTE: We can use the ProcessBuilder class from J2SE 5.0+.
    for further reference check the below link
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=3
    and don't forget to go through API documentation for java.lang package
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/package-summary.html
    and if you want to implement it through Java which provides you a list of Files & directories in the present directory here is an example of such code snippet REF:as insisted by my fellow poster.
    File file = new File("<present_directory_path>");
    if(file.isDirectory()){
       String fileNames[] = file.list();
            for(String fileName:fileNames)
               System.out.println(fileName);
      fileNames = null;
            or for detailed info use
             File files[] = file.listFiles();
             for(File fileEntity:files)
                System.out.println("FILENAME:"+fileEntity.getName+",IS FOLDER:"+fileEntity.isFolder()+",ABSOLUTE PATH:"+fileEntity.toString()+"FILE SIZE:"+fileEntity.length());
             files = null;
    }and please do not forget to go through File API Documentation provided as recommended by my fellow poster.
    hope this might help :)
    REGARDS,
    RaHuL

  • How to execute Operating System commands from Stored procedure.

    Any help on how to execute Operating System commands from stored procedures will be appreciated.
    Nanditha.

    Search the forums for 'External Procedure' and you will find example code that has been posted before.

  • How to execute a Unix Command in java

    Hi, Iam trying to execute a unix command on Sun Solaris by passing that command to a java program. How can I achieve this?
    Thanks in advance.

    Have a look at the javadoc around the Runtime.exec() method. If the command is a shell command then you might have to execute a shell as well as the command.
    For example, if you wanted to run a unix command 'ls -l > output.txt' the you might have to pass the following string into the exec() method,
    "/bin/sh ls -l > output.txt'

  • IS there an easy way to execute a shell command and capture its output...

    From an application? I am thinking of using fork and then waiting for the PID to finish and write the output to a file which I then read, but this seems clunky. Also there are big warnings about frameworks getting hosed if you use fork, although the "Forked" process will exec the shell command and the one that gets the PID the original process might be 'safe' from this framework corruption. I am not certain of this, it is just a guess.
    If there was something like a process class where I could specify the executable and parameters, and read from it's std out until the process completed, that would be better. Or even get a callback when the process exited and an asynchronous callback for each line of data it produced.

    That was just in response to OrangeKay implied accusation that I was some kind of hard-core Microsoft programmer that sneered at apple programmers.
    You may want to book mark this, I will go over a brief history which should clear a lot of things up, about me, and about what I am doing.
    Lets turn the clock back to 1998: I graduate from a university with a BS in Computer science. I had been interning at a local defense contractor writing missile testing software. This was on a proprietary hardware and so there was no "Microsoft" involved. At this point I think Bill Gates = Satan. Microsoft = Kingdom of Evil.
    I get a job as a video game programmer. I write code from the Playstation, then the Playstation 2 and Gamecube. I do this for several years and again I have zero interest / knowledge of the Microsoft world beyond it being the OS which I am forced to use to play my games on. I had fought this by trying to use OS Warp and other things, but eventually since I mainly had a PC for games I had to get a windows OS, the first being NT 3.51 and then Win98 cause NT4.0 didn't support past directx 3 and everyone was using directX 5 or 6 (I do not remember).
    As video game companies go, they do not last. Everyone wants to write video games, anyone with some cash wants to start a company. 1 in 1000 will make it 5 years. Needless to say, as our company began to tank, I got laid off, along with my entire team. I have cash in the bank, no big deal, right?
    Well the economy started to suck, video game developers were closing down like crazy so the market was saturated with x-video game developers. 2 Years go by, no job, and almost no money. Then I get a call from some guy who wants me to come for an interview about 75 miles away. It is in a place I do not want to go. So they interview me, and ask me a bunch of general programming questions.
    I leave the place, and by the time I get home there is a message on my machine asking me if I would take the job at a ridiculously high salary (I live in an area where the cost of living is very low). Well I am about out of money and its a job offer with a huge salary, so I take it.
    I get there and guess what? I get to work on this "agent" that runs on windows boxes. I have NO IDEA how to program on windows. Windows is evil, why would I want to taint myself with this vile Microsoft APIs? I really have no choice, I have to learn how to develop on windows. I get to use visual studio 6, which I do not understand because I used the Borland compilers (Borland != Microsoft).
    Well I start to slug through it all and get familiar with MSDN and CodeProject and CodeGuru. As the years pass, I begining applicate the examples and detailed documentation that MSDN has. I have a start page on MSDN which covers every category of operation which will take you through a tree of choices and lead you to the exact area related API calls you will need to use to do whatever you want. Now I do not think MS = Evil anymore. I switch to DevStudio 2005 which is really nice. The debugging, IDE, and everything is great.
    Now the other half of this application resides on a server. That server is a Linux box, and the server app is written in Java. My stuff is still C++.
    One day, I get a request, and a eMac with 10.4 PPC to make a Mac version. Now I am at the point of Mac programming as I was with Windows when I started. I didn't know anything about it. I was looking for CodeWarrior cause I used that in the past, but alas, CodeWarrior is no more. I get XCode. I see all sorts of options to make a project. BSD project, Carbon, Cocoa, etc... What the heck any of these. I can guess the BSD one is very basic, but I do not understand Carbon vs Cocoa.
    So what do I do? I make a basic carbon app and make a basic Cocoa app. The carbon app looks like some kind of C++ framework. The Cocoa app? "Is this another language like Java or C#? It doesn't look like a C++ language."
    Guess which choice I make. Carbon. I struggle through this looking at the docs, posting on CodeGuru and whatnot until someone finally tells me about these forums and warns me about how unfriendly people are. So I make an account and start asking questions. I eventually get my app to be multi-platform to run on windows and Mac by using some API abstractions which are easy to do since I had abstracted the Windows API by my own class wrappers.
    I ask a lot of questions, very few are ever answered because I am not asking about simple things, like making windows and how to get button clicks and that stuff. I am asking stuff like, "How do you change the DNS? or How do I know when a user is about to log out?" Currently on my side list as I type this, I have 27 unresolved questions. I probably found workaround for most of them, or figured it out eventually.
    On this forum mostly people are helpful when the do respond, except for OrangeKay. He definitely has a chip on his shoulder.
    Over the past few years my Opinion of MS has improved greatly while my opinion of Macs (from the programmer's point of view) has dropped considerably. XCode still isn't as good as VS6 which is like 15 years old, never mind Dev studio 2005 or 2008. The documentation is scattered, not easy to find, occasionally wrong, or simply missing. The examples may not even compile or contain non-existent functions. It is unbelievable how bad it is.
    If Steve Jobbs wants to really get a large coder population he ought to spend some of those billions (or is it trillions) of dollars on a team that will re-write the current documentation in a correct, easy to understand, with full examples, arranged in a logical manner for everyone to use. He should say, "See MSDN online? I want something like that, only better, it has to be MUCH better." Then he should say to the XCode team, "Look at DevStudio 2008. XCode should do EVERYTHING that does. Once that is done, IMPROVE XCode even more to make 2008 look like a joke."
    To bad the Developer aspect of the "Apple Experience" has not gotten "End User" treatment. Then it would be a joy to develop on Macs.
    So here I am asking for help on certain things. You wonder why I do not use Cocoa. Maybe I should, maybe I shouldn't. My first look didn't look promising, and a quick look at the docs is all about GUI's. My app has NO GUI. Again, Cocoa? Maybe it will still work, but the examples and stuff I see are all about GUIs.
    When I get time, I will look at cocoa even further. MFC on windows is MOSTLY about GUI stuff, but there is a small section of it that does not deal with GUIs. CString is a great MFC class. I had to get rid of it though cause Mac's do not have a similar class. I use CStdString which is a platform agnostic CString replacement.
    I hope you are all a little more enlightened. BTW my Application which runs on Mac's and PCs on no less then 3 MILLION Machines has not crashed ONCE in the past 2 years. There have been bugs, but nothing that crashed it. The bugs were mostly unforeseen situations, like what if the guy has 15 network adapters that are all LIVE? I didn't plan for that, there were complications, the server got some strange data, but it didn't crash (My app, not the server. It crashes on occasion still). Are there bugs in my code? I am sure there are, but I do not know of any, because if I did, it would be fixed.

  • How to execute a cvs command using System Call?

    hi all,
    how to execute a cvs login command using system call ?
    thanks,
    dam

    To anyone that reached this post and still dont have a hint, try this small sample - it logs on CVS using installed CVSNT and execute a fake update:
    package testeCVS;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    public class execCMD
        String password="yourPassword";
        String directory="C:\\CVS\\yourPathToProject";
        //send commands to CVS and shows the resulting screen
        public int sendCMD(String[] command) throws IOException, InterruptedException
            ProcessBuilder pb = new ProcessBuilder(command);
            pb.directory(new File(directory));
            pb.redirectErrorStream(true); // merge stdout and stderr
            Process p = pb.start();
            InputStreamReader isr = new  InputStreamReader(p.getInputStream());
            BufferedReader br = new BufferedReader(isr);
            String lineRead;
            StringBuilder buffer=new StringBuilder();
            System.out.println("Return of shell:");
            while ((lineRead = br.readLine()) != null)
                buffer.append(lineRead + "\n");
            System.out.println(buffer.toString());
            return p.waitFor();
        //send commands to CVS, send the password after the prompt and show the resulting screen
        public int sendDialogCMD(String[] command) throws IOException, InterruptedException
            ProcessBuilder pb = new ProcessBuilder(command);
            pb.directory(new File(directory));
            pb.redirectErrorStream(true); // merge stdout and stderr
            Process p = pb.start();
            PrintWriter writer = new PrintWriter( new OutputStreamWriter( p.getOutputStream() ));
            writer.println( password );
            writer.flush();
            InputStreamReader isr = new  InputStreamReader(p.getInputStream());
            BufferedReader br = new BufferedReader(isr);
            String lineRead;
            StringBuilder buffer=new StringBuilder();
            System.out.println("Return of shell:");
            while ((lineRead = br.readLine()) != null)
                buffer.append(lineRead + "\n");
            System.out.println(buffer.toString());
            return  p.waitFor();
        public static void main(String a[]) throws IOException, InterruptedException
            execCMD e=new execCMD();
            String[] command = new String[5];
            command[0] = "cvs";
            command[1] = "-q";
            command[2] = "-d";
            command[3] = ":pserver:yourUserID@localhost:2402/path/of/yourProject"; //in this case using CVS port 2402
            command[4] = "login";
            System.out.println("exit value=" + e.sendDialogCMD(command));
            command = new String[8];
            command[0] = "cvs";
            command[1] = "-q";
            command[2] = "-d";
            command[3] = ":pserver:yourUserID@localhost:2402/path/of/yourProject";
            command[4] = "-n";
            command[5] = "-q";
            command[6] = "update";
            command[7] = "-dA";
            System.out.println("exit value=" + e.sendCMD(command));
    }It is possible to send the password on the same command, but I had problems when the password had the character '@' because CVSNT took it as the separator between the username and server name. In that case the command is: ":pserver:yourUserID:yourPassword@localhost:2402/path/of/yourProject"

  • How can i call shell command in JSP?

    My OS is Linux, and my WWW server is Tomcat,
    can i call shell command , such as gcc or setup,
    If yes, how can i? Would you give a source example?
    Thank you!

    Hi,
    I did this simple class to launch a process and after the cose there is an example to use it:
    import java.io.*;
    import java.util.*;
    public class ProcessExec {
    private String[] command;
    private StreamGobbler errorGobbler;
    private StreamGobbler outputGobbler;
    public ProcessExec() {
    public ProcessExec ( String[] command) {
    this.command = command;
    this.errorGobbler = null;
    this.outputGobbler = null;
    public String[] getCommand() {
    return ( this.command );
    public void setCommand( String[] command ) {
    this.command = command;
    public void exec() {
    try{
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(this.command);
    // any error message?
    errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
    // any output?
    outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
    // kick them off
    errorGobbler.start();
    outputGobbler.start();
    }catch (Throwable t){
    t.printStackTrace();
    }//catch
    public String getErrorMessage() {
    while ( this.errorGobbler.isAlive() ) {;}
    return ( this.errorGobbler.getResult().toString() );
    public String getOutputMessage() {
    while ( this.outputGobbler.isAlive() ) {;}
    return ( this.outputGobbler.getResult().toString() );
    } // ProcessExec
    Example to use it:
    try {
    ProcessExec pe = new ProcessExec( command );
    pe.exec();
    errorMessage = pe.getErrorMessage();
    outputMessage = pe.getOutputMessage();
    } catch ( Exception e ) {
    System.out.println (e);
    As you can guess the string "command" must be the command you have to launch and errorMessage and outputMessage will contain the error and the output that the process will generate.
    Try it; i hope this will help you.
    Cheers.
    Stefano

  • How to execute any cmd command from java application?

    Hi all,
    How to execute or call any command of cmd from java application??
    Is there any method to do so??
    Or, is it possible to do it using Runtime.exec() ??? And if so, how to use it, please explain with ab example...
    I'll highly appreciate....
    Thank you.

    If google would be the best option, then I would not be on Sun's forums and I would not have asked experts like you, sir !! :-)
    Neway, I got the solution from PhHein !!
    Good link indeed..
    Cheers..

  • How to append linux shell command output to MariaDB?

    That link gave me an idea, I can create an .sql template file with the "insert" query, dump the shell command output to a text file (>), then use "grep" and "sed" to append the desired parts of the command's output file to that .sql file and then execute the .sql file. What do you think?

    I haven't done this myself, but it is probably something along the lines of the answer provided in this link:
    http://stackoverflow.com/questions/3900496/using-shell-script-to-insert-data-into-remote-mysql-datab...
    

Maybe you are looking for