Executing system commands and capturing results

How do I get the result of executing a system command using Runtime? For example, if I execute "cmd /c dir", how do I get to the result of the dir command from the Process that is returned?

Process p = Runtime.getRuntime.exec("...");
InputStream in = p.getOutputStream();
// now read the "in" stream just as you would any
other stream.Slight typo getRuntime(), but it's close...

Similar Messages

  • Executing external command and program in background

    Hi,
    how to execute external command and external program in background.
    please provide me some tips on the same.
    while creating external command, what is the significance of "operating system command" and "parameters for operating system command".
    Thanks,
    Dinesh.

    Hi,
    You can define external commands using transaction code SM69.
    External commands are commands which would be executed at your operating 
    system with or without parameters.
    Operating system commands are those which you execute at OS level like
    mkdir, cat, rm, cp, ls
    Parameters are options that you add to os commands to get more functionalities.
    like, < ls -l > : will give you a long listing of files where " l " is the parameter
            < ls -lt > : will give you a long listing with last changed file at top where " lt " is the parameter.
    You can mention these in SM69 when you define the external commands.
    Now, in order to execute these in your background job. In the steps click on "external command" and give your command name in SM36 while creating your job.
    " Points for solution ".
    Thanks and Regards,
    Sandeep.

  • I executed stopsap command and I rebooted server.Now I can not use startsap

    I executed stopsap command and rebooted server.Now I can not use startsap
    I use Oracle Database
    System gives me message below:
    Checking ORC Database
    ABAP database is not avalable via R3Trans
    ABAP Database ORC must be started on remote server
    How can I solve this problem?
    Thanks.

    Hello Cemil,
    Could you save the output that the script startsap returns to a file and upload it somewhere. Also the startsap logs, the location of which you could see when you run the startsap script. You could use http://www.rapidshare.com/ to upload the files.
    Regards,
    Ventsi Tsachev
    Technology Development Support (J2EE Engine)
    SAP Labs, Palo Alto, Ca (USA)

  • 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.

  • Executing System Commands In Java

    Hi,
         I am not sure if this is a bug � or I am just doing this wrong. I have
    written a program to move files into ~/.trash/ . My problem is that this
    works only for files without spaces � but for files with spaces it will
    not work. Some of my code is below.
    I have temporarily uploaded the complete file at
    http://www.geocities.com/carmaski/Remove.java
    public static void main(String args[]) {
    String currDir = System.getProperty("user.dir") + "/";
    String trashDir = "\" \"/home/masca/.trash/";
    String commandString = "";
    for (int i = 0; i < args.length; i++ ) {
    File tmpFile = new File(currDir + args);
    if(tmpFile.exists()) {
    commandString = "mv \"" + currDir + args[i] + trashDir
    + args[i] + getTimeTag() + "\"";
    System.out.println("The command would be -- " +
    commandString);
    try {
    Process p = Runtime.getRuntime().exec(commandString);
    catch (IOException e) {
    e.printStackTrace();
    System.exit(-1);
    As an example I tried � this with a file that has a space � and I get
    the following output.
    The command would be -- mv "/home/masca/WORK/Text File"
    "/home/masca/.trash/Text File_2005.04.17_04hrs:25mins:36secs"
    However the file remains without being moved.
    I cannot understand why the mv command does not work in java. If I
    manually copy this to the command line I can get the file to work. It
    should be noted that this program works perfectly if the file does not
    have a space.
    Regards,
    Rio

    Use File.separator or simply / instead of Windows
    backslashes.
    - SaishI think OP is on a unix machine, and he still needs to escape the spaces. The escape character is, of course, a back-slash.
    Depending on the shell (my experience is with bash), to execute the command mv Test File.txt newTest File.txt, the file names either need to be double-quoted so that the command shell will treat them as a single token (I think that will work), or the spaces need to be escaped (I know that will work). In java, to include a single \ in a literal String, you need to escape the escape character, which is why I think two \\ are needed in the String, so that one will survive to be passed on to the exec command.
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Please help how to run System commands and batch files thru java program

    Sir,
    I want execute OS commands like dir,cls..etc and batch files,.exe filesthru java program.
    I have tried it sofar thru Runtime.getRuntime().exec("execute.bat");
    but it is not working.anybody knows about how to run the system commands thru java please give me the code.
    thank you,
    regards,
    j.mouli

    I've seen other posts with this questions, and answers. Unfortunately I didn't pay much attention. But the basic idea is to exec command.com and pass the specifc batch or command as an argument.

  • Executing system commands query

    I'm only just starting to program Java although I do have a good grounding in programming other languages so it is probably more a question of familarity, but hopefully someone can answer this problem I am having.
    What I am trying to do is to execute TFTP on a Windows NT machine roughly every 5 seconds to get a file. To do this I have created a thread and within "public void run" I have a loop which contains something along the lines of:
    Runtime.getRuntime().exec( "C:\\WINNT\\system32\\tftp.exe <ipaddress> get <filename>" );
    Where I would specifiy a real IP address and filename.
    I then do a sleep on the current thread to make it pause for a while.
    The good news is it fetches the file every few seconds as I wanted. The bad news is it creates a new TFTP process each time and so it keeps using more and more memory.
    Now I'm sure there are better ways to do this but I am working things out as I go along. The finished program will use an infinite loop which will run out of memory.
    Can anyone recommend a solution or method to do this? Should I not bother with the thread, and what would be the best method to make it pause without killing processor time?
    If possible can anyone mail me directly. Thanks in advance.
    Mark.

    No I must quite specifically use TFTP. The scenario is information is entered via a FORM on a web page. The data is passed from the client to a server where I parse it using perl and write out the data in the necessary form to a file.
    The java file I am writing then runs continually fetching this file every few seconds for another program to read. The other program reads the data every few seconds and uses one of the fields in the file to identify if it has changed since the last time it was fetched, if so it can act on the new data.
    Using TFTP I can call it with a command line function to invoke TFTP to connect and fetch a file in one line. This seems much simpler using an existing executable than hand crafting code to do the same job.
    I've managed to write something in C++ which performs the task. Java seems a bit more ackwared as it discourages you using system commands as it means the code is not portable.
    However I originally wrote this as a Java file to expand my knowledge and as such I would like a proper solution.
    Thanks for the suggestion though. I will have a look just out of curiosity now.
    Mark.

  • How to execute system command from java program

    Hi all,
    I want to change directory path and then execute bash and other unix commands from a java program. When I execute them separately, it's working. Even in different try-catch block it's working but when I try to incorporate both of them in same try-catch block, I am not able to execute the commands. The change directory command works but it won't show me the effects of the bash and other commands.
    Suggestions??

    The code I am using is....
    try
    String str="cd D:\\Test";
    Process p=Runtime.getRuntime().exec("cmd /c cd
    "+str);your str string is already having cd in it but again you ar giving cd as part of this command also please check this,i will suggest you to remove cd from str
    Process p1=Runtime.getRuntime().exec("cmd /c mkdir
    "+str+"\\test_folder");you should say mkdir once you change your path,but here you are saying mkdir first and then cd D:\Test(this is because of str)..please check this
    Process p2=Runtime.getRuntime().exec("cmd /c bash");
    Process p3=Runtime.getRuntime().exec("cmd /c echo
    himanshu>name.txt");
    catch(IOException e)
    System.err.println("Error on exec() method");
    e.printStackTrace();
    Message was edited by:
    ragas

  • How to execute System command through Applet

    Hi all,
    How can I execute a System command through Applet.
    I have written a code Runtime.exec("ls") in my applet but it gives me
    this execption even if I certify the applet ->
    java.security.AccessControlException: access denied (java.io.FilePermission <<ALL FILES>> execute)
         at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
         at java.security.AccessController.checkPermission(AccessController.java:399)
         at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
         at java.lang.SecurityManager.checkExec(SecurityManager.java:802)
         at java.lang.Runtime.exec(Runtime.java:548)
         at java.lang.Runtime.exec(Runtime.java:418)
         at java.lang.Runtime.exec(Runtime.java:361)
         at java.lang.Runtime.exec(Runtime.java:325)
         at Test.init(Test.java:24)
         at sun.applet.AppletPanel.run(AppletPanel.java:344)
         at sun.plugin.navig.motif.MotifAppletViewer.maf_run(MotifAppletViewer.java:123)
         at sun.plugin.navig.motif.MotifAppletViewer.run(MotifAppletViewer.java:119)
         at java.lang.Thread.run(Thread.java:484)
    Thanks,
    Manoj.

    There should be a lesson about this somewhere.
    When you visit a web page, does it ask you if you want to have an applet loaded?
    Answer: No
    So, if you visit a page, and an applet is silently loaded which can then execute commands on your computer, is this good?
    Answer: No
    So why do you want to do this?
    Is it good for anyone?
    I mean, if I want to do "ls", can't I just open a command line? Do I need an applet to do it for me?
    Either you have devious desires or your hacking together something that probably shouldn't be.
    If you want to learn start here:
    http://java.sun.com/docs/books/tutorial/security1.2/index.html
    With the article entitled:
    Quick Tour of Controlling Applets
    Ian

  • Executing system commands like cd on Linux from Java Code

    Hi,
    I need to execute a few system commands (like cd, ls, tar, etc.,) on RedHat Linux 7.1 from Java code. Any ideas plz.
    best wishes,
    Issac

    Since this thread mentioned using the DOS START command
    from an exec(), I was wondering whether anyone else is
    seeing the odd behavior I am.
    Most of the examples showing how to read stdout and stderr
    while the process is running show simple loops that use
    getInputStream and getErrorStream and do read's until they
    get back -1. Most of these examples are insensitive to the
    state of the Process.waitFor that happens elsewhere and sort
    of rely on the -1 and the waitFor happening roughly together.
    Whenever I use this technique to launch an arbitrary DOS
    command (e.g. Runtime.exec("dir")), it works fine, and
    everything seems to terminate as expected.
    However, when my command is something like:
    Runtime.exec("cmd /c start my.bat")
    where I deliberately use the START command to fork off
    a different process, something odd happens.
    Those simple read loops get an initial burst of stdout/stderr
    bytes from the "start" part of the command. But then eventually,
    these loops do a "read" which blocks on those InputStreams. Now,
    even if my Process.waitFor returns (because the start returned
    immediately), those read loops stay blocked **until that script
    started by 'start' runs to completion**. It is like the child
    of the child is holding those streams open somehow.
    I found that by doing something like an InputStream.available() or
    a BufferedReader.ready( ) check before dropping into the read,
    and allowing the Process.waitFor completion to exit those read loops,
    them I get what I expect -- namely immediate return from the START,
    but apparently complete copies of stdout and stderr.
    Curiously, in the case where the reads block until the child process
    started by START terminates, they still don't get the child's/child's
    stdout and stderr. It is just a long duration thread block that
    yields no data.
    Can anyone explain what is happening to a
    Process.getInputStream( ).read()
    when the process immediately does a START and returns? Why would
    the read( ) stay blocked when the START finished launching a new child
    process?
    ... ron cain

  • Supressing Dos window on executing system command

    Hey,
    is there any way to supress the dos window when I call a system dependent .exe or bat file?
    AND
    is there any way to run a .exe file as a background process so that no window of it pops up?
    I use the Runtime.exe() to execute the system command but I'm annoyed by the dos windows it opens up.
    Any help highly appreciated.

    This is an AGE OLD Issue which Sun keep burying. By burying I mean it has been the top of their bugs/requests list many times. They just decide its closed without making any such fixes. The community is not pleased with Suns actions in this respect, blowing off their highest rated request.
    Answer:
    If you start your program with java.exe, then you wont get that window when you do runtime commands. If you start with javaw.exe, you will. They are blaiming it on M$ but most feel its just a silly Sun position and lame attempt to put somethign on M$ that is not really on M$. Sun can do it but they feel their solution is unstable. Most people have ended up making .exes to replace java.exe to get rid of that hideous console window. JBuilder has an interesting (but not my type) solution.
    If you search the top 10 bugs/ requests this one has likely resurfaced as Sun keeps erasing it, but the people keep voting it back to the top...

  • GUI that open a Linux terminal, run commands and retrieve results

    Hi
    I am currently designing a GUI that should make it easier for users to execute a command line statement and read the information that is returned.
    I should not have any issues with the actual GUI, but I have not been able to find any examples to help with how to open a command terminal, enter a command and retrieve the results. I am aware that using a screen scraper is a possibility, but if anyone is aware of any examples to achieve this, that would be great.
    Thanks
    Matt

    Is the command line app a simple, straightforward one
    that just prints its output? (Eg. ls, dmesg, or any application
    that simply print results without reading input)
    If so, try this tutorial on calling a program
    and reading its output:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    But if your commandline app is a rich-interactive one
    (eg. a full screen menu program or full screen text editor
    or something), then it's much much more complicated.

  • Executing system command thru command line by passing it to a server

    Hello,
    I would like to know if there is any way by which I can call a system command through a java program . This system command takes parameters. If yes then how do i pass these paramaeters. This program will be called thru a sheel scripts and the parameters may vary...

    If I just look at the question in your post, I would say the answer is to call Runtime.getRuntime().exec("the system command"). But the title of the post mentioned passing it to a server; I won't attempt to answer that without knowing what it's all about.

  • Execute system command line instructions

    Hi,
    suppose that my java program has to execute a system command line instrction(let's say dir/p for dos or ls * f or linux)
    how can we execute these system command line instructions programmatically from within a java program?
    thanks indeed for helping...

    i want to thank jfbriere for the usefull link he/she provides me with. 1- He
    2- You're welcome :-)

  • Execute System Commands

    Hey all
    I need to write Java application that executes windows system commands. In the following example I tried to execute the command DATE /T but i got an exception. Could any one help ?
    import java.io.*;
    public class Shell {
        public static void main(String[] args) {
            String s = null;
            try {
                Process p = Runtime.getRuntime().exec("date /t");
                BufferedReader input = new BufferedReader(
                        new InputStreamReader(p.getInputStream()));
                System.out.println("Here's the standard output of the command: ");
                while ((s = input.readLine()) != null) {
                    System.out.println(s);
            } catch (IOException e) {
                e.printStackTrace();
    }

    hi,
    give command as "cmd /c date /t"
    to execute any dos commands using exec() method, you have to send those commands as parameters to the cmd.exe .
    regards,
    Mahender

Maybe you are looking for