Execute a command or another program

Can someone please how I can execute an operating system command or another program from Java. Example I want to execute the Unix command ls from Java.
Thanks
Peter Loo

Hi Peter,
Can someone please how I can execute an operating
system command or another program from Java. Example I
want to execute the Unix command ls from Java.I think you could use the following code:
try{
Runtime.getRuntime().exec("ls");
}catch(IOException ioe){
   // some exception handler...
}Hope that helps
Adrian

Similar Messages

  • How to execute dos command in Java program?

    In Perl, it has System(command) to call dos command.
    Does java have this thing?
    or any other way to execute dos command in java program?
    Because i must call javacto compile a file when the user inputed a java file name.

    Look in the Runtime class, it is implemented using the Singleton design pattern so you have to use the static method getRuntime to get its only instance, on that instance you can invoke methods like
    exec(String command) that will execute that command in a dos shell.
    Regards,
    Gerrit.

  • 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

  • Execute Unix command from Java program running on windows

    Hello,
    I need to write a java program that fetches file count in a particular unix machine directory. But java program will be running on windows machine.
    The program should execute unix list command and fetch the output of that command.
    Can anyone help me on this?
    Thanks.

    Hi there,
    I had a similiar problem, though years ago. It was to have a java program execute any other. Lately, I've had to have a java program running on a unix machine execute a shell script. Entirely two different scenarios. I'm not sure what you will need for your app, but look into this:
    Java Native Interface for executing C/C++ code.
    C/C++ Code for launching the program you need to run.
    java.lang.Runtime(?).exec(....)
    With a combination of that stuff, you can make a launcher for any os that has Java running on it, and with Runtime, you can exec() pretty near any sort of unix shell or app command you'd like.
    Good luck.
    Tim

  • Executing system command (third party program) from extend script without showing console on windows

    I am using following code on mac:
    app.system("/path/to/external/executable &");
    It runs external program in background (without showing console/terminal).
    On windows I tried many things like:
    app.system('start "" "/path/to/external/executable"');
    app.system('start "" /B "/path/to/external/executable"');
    And I was also trying to solve it using visual basic.
    Unfortunately everytime I use app.system(...) then windows console is showed on the screen for half of the second, then it disappears and progrm runs in background. Is it possible to avoid showing console window? Maybe there is another way of executing third party program?

    You can try to save a vbscript :
    Dim objShell
    Set objShell = WScript.CreateObject( "WScript.Shell" )
    objShell.Run("""\path\to\external\executable"""), 0, True
    Set objShell = Nothing
    than just execute it from javascript: 
    var vbFile = new File("path to your vbscript file")
    vb.execute();

  • How  to execute os command from ABAP program?

    I want to execute some window commands from ABAP. What is the way to do it?

    Hi,
    See ht e coding below, I have used these Fm to connect to FTP server and get the Files..
    *types for the ftp command result internal table
    TYPES : BEGIN OF ty_result,
            text TYPE char512,
            END OF ty_result.
    data it_result type standard table of ty_result.
    *Connect to the FTP server
      CALL FUNCTION 'FTP_CONNECT'
        EXPORTING
          user            = lv_user           " user name pass word to connect
          password        = l_v_pwd
          host            = 'dev.eu.pm.com' " Host name here
          rfc_destination = 'SAPFTPA'   "destination name
    *Ask your functional people for the above data
        IMPORTING
          handle          = v_handle
        EXCEPTIONS
          not_connected   = 1
          OTHERS          = 2.
      IF sy-subrc <> 0.
      ENDIF.
    *Changing directory
      CONCATENATE 'cd' '<file path>' INTO l_v_cmd SEPARATED BY space.
    you can also ser 'DIR in l_v_cmd which opens the directory and all the folders *get into it_result table..
    *Execute the FTP Command
      CALL FUNCTION 'FTP_COMMAND'
        EXPORTING
          handle        = v_handle
          command       = l_v_cmd
        TABLES
          data          = it_result
        EXCEPTIONS
          tcpip_error   = 1
          command_error = 2
          data_error    = 3
          OTHERS        = 4.
      IF sy-subrc <> 0.
      ENDIF.
    rewards if useful,
    regards,
    nazeer

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

  • Executing multiple commands

    how to execute multiple commands through java programming .I tried with the code
    Process pro=Runtime.getRuntime().exec("cmd /c cd C:\\Symbian\\Carbide\\MyXmlParserWeb\\group\\s60_3rd");
              pro.waitFor();
              BufferedReader reader=new BufferedReader(new InputStreamReader(pro.getInputStream()));
              String line=reader.readLine();
              while(line!=null)
              System.out.println(line);
              line=reader.readLine();
              for(int i=0;i<2;i++){
                   try {
                        Thread.sleep(500);
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
              Process pro4=Runtime.getRuntime().exec("bldmake clean");
              pro.waitFor();
              BufferedReader reader4=new BufferedReader(new InputStreamReader(pro4.getInputStream()));
              String line4=reader4.readLine();
              while(line4!=null)
              System.out.println(line4);
              line4=reader4.readLine();
              for(int i=0;i<2;i++){
                   try {
                        Thread.sleep(500);
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
              Process pro1=Runtime.getRuntime().exec("bldmake bldfiles");
              pro1.waitFor();
              BufferedReader reader1=new BufferedReader(new InputStreamReader(pro1.getInputStream()));
              String line1=reader1.readLine();
              while(line1!=null)
              System.out.println(line1);
              line1=reader.readLine();
              for(int i=0;i<2;i++){
                   try {
                        Thread.sleep(500);
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
              }

    class MainClass extends Thread {
         InputStream is;
         String type;
         OutputStream os;
         MainClass(InputStream is, String type)
         this(is, type, null);
         MainClass(InputStream is, String type, OutputStream redirect)
         this.is = is;
         this.type = type;
         this.os = redirect;
         public void run()
         try
         PrintWriter pw = null;
         if (os != null)
         pw = new PrintWriter(os);
         InputStreamReader isr = new InputStreamReader(is);
         BufferedReader br = new BufferedReader(isr);
         String line=null;
         while ( (line = br.readLine()) != null)
         if (pw != null)
         pw.println(line);
         System.out.println(type + ">" + line);
         if (pw != null)
         pw.flush();
         } catch (IOException ioe)
         ioe.printStackTrace();
         public static void main(String args[])
         if (args.length < 1)
         System.out.println("USAGE java GoodWinRedirect <outputfile>");
         System.exit(1);
         try
         FileOutputStream fos = new FileOutputStream(args[0]);
         Runtime rt = Runtime.getRuntime();
         Process proc = rt.exec("cmd.exe");
         // any error message?
         MainClass errorGobbler = new
         MainClass(proc.getErrorStream(), "ERROR");
         // any output?
         MainClass outputGobbler = new
         MainClass(proc.getInputStream(), "output", fos);
         // kick them off
         errorGobbler.start();
         outputGobbler.start();
         // any error???
         int exitVal = proc.waitFor();
         System.out.println("ExitValue: " + exitVal);
         fos.flush();
         fos.close();
         } catch (Throwable t)
         t.printStackTrace();
    i have modified the code again.but still no result.....

  • Why am I being told that a JPEG file that I made changes to in Photoshop 6 (CS6) can't be saved?  The message I get says that either the file is locked and I don't have permission to execute this or another program is using this file.

    i recently purchased a 21.5 iMac with Yosemite (10.10.1) and was disappointed to discover that my CS6 programs are not functioning correctly.  I am unable to use the "Save As" command  when making changes to a JPEG file in Photoshop.  The message I get says that either another program is using the file or it is locked and I don't have permission to execute that command.  I'm experiencing a similar problem in Bridge when trying to move an unwanted file to the Trash.  Again, I get a message telling me that i don't have permission to do this.  Lastly, I'm unable to open any Camera Raw files.  Any suggestions?  I had no problems with the Mavericks OS on my old iMac and although it's much slower, I'm tempted to go back to using my old iMac.  At this point, I feel as if I've just wasted $2300+ (tax included). 

    Back up all data before proceeding.
    This procedure will unlock all your user files (not system files) and reset their ownership, permissions, and access controls to the default. If you've intentionally set special values for those attributes on any of your files, they will be reverted. In that case, either stop here, or be prepared to recreate the settings if necessary. Do so only after verifying that those settings didn't cause the problem. If none of this is meaningful to you, you don't need to worry about it, but you do need to follow the instructions below.
    Step 1
    If you have more than one user, and the one in question is not an administrator, then go to Step 2.
    Triple-click anywhere in the following line on this page to select it:
    sudo find ~ $TMPDIR.. -exec chflags -h nouchg,nouappnd,noschg,nosappnd {} + -exec chown -h $UID {} + -exec chmod +rw {} + -exec chmod -h -N {} + -type d -exec chmod -h +x {} + 2>&-
    Copy the selected text to the Clipboard by pressing the key combination command-C.
    Launch the built-in Terminal application in any of the following ways:
    ☞ Enter the first few letters of its name into a Spotlight search. Select it in the results (it should be at the top.)
    ☞ In the Finder, select Go ▹ Utilities from the menu bar, or press the key combination shift-command-U. The application is in the folder that opens.
    ☞ Open LaunchPad and start typing the name.
    Paste into the Terminal window by pressing command-V. I've tested these instructions only with the Safari web browser. If you use another browser, you may have to press the return key after pasting.
    You'll be prompted for your login password, which won't be displayed when you type it. Type carefully and then press return. You may get a one-time warning to be careful. If you don’t have a login password, you’ll need to set one before you can run the command. If you see a message that your username "is not in the sudoers file," then you're not logged in as an administrator.
    The command may take several minutes to run, depending on how many files you have. Wait for a new line ending in a dollar sign ($) to appear, then quit Terminal.
    Step 2 (optional)
    Take this step only if you have trouble with Step 1, if you prefer not to take it, or if it doesn't solve the problem.
    Start up in Recovery mode. When the OS X Utilities screen appears, select
              Utilities ▹ Terminal
    from the menu bar. A Terminal window will open. In that window, type this:
    resetp
    Press the tab key. The partial command you typed will automatically be completed to this:
    resetpassword
    Press return. A Reset Password window will open. You’re not going to reset a password.
    Select your startup volume ("Macintosh HD," unless you gave it a different name) if not already selected.
    Select your username from the menu labeled Select the user account if not already selected.
    Under Reset Home Directory Permissions and ACLs, click the Reset button.
    Select
               ▹ Restart
    from the menu bar.

  • Executing another program with Java?

    I'm relatively new to Java. I'd like to build a process-monitoring program that will allow me to determine the status of certain processes on the machine. In order to do this I need to know if Java can execute (and then of course read the output of) another program, in this case, the Unix 'ps' command.
    Thanks.
    David

    yeah: look at the java.lang.Runtime and java.lang.Process APIs, specifically Runtime.exec . There are a ton of discussions about those APIs in this forum, so you can probably find some code examples as well, if you do a search... Take care.

  • Executing a report program in background from another program

    Hi Experts,
    I developed a report to display material change history based on change date range. Report is taking much time (around 15-20 mins) as I'm hitting CDPOS and CDHDR tables. User wants to execute the report in foreground because he/she can give selection criteria that is required everytime.
    So, my requirment is now to create another program with same selection screen elements which will execute the original program in background. In the new program, we will be just capturing the selection elements and will pass them to original program to run in background and display a message to user without wait for the background job to complete. Original program should send an email to an fixed email id with the report output as attachment (for example excel file).
    Please suggest.
    Thanks in Advance,
    Siva Sankar

    Hi Siva,
    Please see the link
    http://help.sap.com/saphelp_nw04/helpdata/EN/2a/fa01dd493111d182b70000e829fbfe/content.htm
    Regarding a Change Document Function Module ----- VERY VERY Urgent
    When using function modules , I dont think you can directly get data based on material and plant . these function modules usualy works with object class and creation date .
    Once you retrieve the data using the function modules you have to filter out the unncecessary data based on your selection screen conditions .
    Regards,
    Ratheesh BS
    Edited by: Ratheesh Bhaskarapillai Suseeladev on Mar 8, 2012 5:19 AM
    Regarding a Change Document Function Module ----- VERY VERY Urgent

  • Could not save Preferences because the file is locked, you do not have necessary access permissions, or another program is using the file. Use the 'Get Info' command in the Finder to ensure the file is unlocked and you have permission to access the file.

    I have this massage every time close ps cc
    Could not save Preferences because the file is locked, you do not have necessary access permissions, or another program is using the file. Use the ‘Get Info’ command in the Finder to ensure the file is unlocked and you have permission to access the file. If the problem persists, save the document to a different file or duplicate it in the Finder.

    You may get better help in Photoshop General Discussion
    The Cloud forum is not about using individual programs
    The Cloud forum is about the Cloud as a delivery & install process
    If you will start at the Forums Index https://forums.adobe.com/welcome
    You will be able to select a forum for the specific Adobe product(s) you use
    Click the "down arrow" symbol on the right (where it says All communities) to open the drop down list and scroll
    If FINDER means Mac, read below (and try to give more information when asking a question)
    Mac 10.9.3 workaround https://forums.adobe.com/thread/1489922
    Enable Mac Root User https://forums.adobe.com/thread/1156604
    -more Root User http://forums.adobe.com/thread/879931
    -and more root user http://forums.adobe.com/thread/940869?tstart=0

  • Execute a command in an external program.

    Hi all,
    I have a little question. I want to execute a command (ctrl+F1) in an external program. This program is already open, so i dont need to execute it. Is there a way to get the focus in this program and automaticly execute my command? I have checked around and all i found was how to execute the program.
    Thanks alot
    Alex

    I want to execute a command (ctrl+F1)Thats a key stroke, not a command.
    in an external program.I always ask this, but what is an internal program?
    Is there a way to get the focus in this program and automaticly execute my command?Kind of. java.awt.Robot provides methods to simulate mouse and keyboard events. If you know where the window is on the screen, you could focus it using the Robot (move the mouse over it and click) and then issue a key event.
    Not too easy.

  • How:Execute OS commands from a Java program

    hi,
    is it possible to execute an OS command from a java program, as in C/C++? if yes, plz give the details.
    thanx

    In the future try searching the forum before posting. Using keywords like "execute os commands" would lead you to several postings on this topic.
    Note the keywords where taken directly from you subject line. With practice you learn which keywords to use to yield the best search results.

  • Execute Command fron Java Program

    Hi All,
    I am trying to execute a command from Java Application, but iam not getting any result. My problem is:-
    1- Open a terminal.
    2- execute command.
    The same is working fine in windows , the step for windows are:-
    1- execute cmd.exe
    2- go to prompt
    3- execute command.
    How to do it for Solaris 10 ??? Any cmd.exe equivalent for solaris terminal???

    This is done in the exact same way. You open a terminal (depending on your gui its called "console" or "this computer" (CDE), and "Gnome console" (iirc) in the Java desktop) and then you're home free. "javac", "java", etc. should all be in your search path.
    If not look in /usr/java.

Maybe you are looking for

  • Errors starting web server after patch 6

    I just applied 2005Q4 Patch 6 to the Access Manager, redeployed the web apps using amsilent and when I restart the Sun One Web Server 6.1SP8 there's a stack trace. How can I troubleshoot some of these errors and figure out what's wrong? It appears a

  • Print spreads problem

    I have a 4 page document that was set up without facing pages and all 4 pages in a row. Think of a fold out ad in the center of a magazine that folds out on both sides to reveal 4 separate but connected pages. Starting from the left, number the pages

  • Sync Sound, Easy Answer Come on guys

    Wow Can;t Belive I am asking this one, I am syncing sound from a dat recorder to dv captured footage. For the life of me I cannot create independant subclips. Our original capture was not broken down into takes, so we have sub clipped all of the clip

  • Mass Update of date in Qualified  table

    I having problem in updating End availability date in Partner Specific Data (which is a qualified table). How can do a mass update of selected records. I have written an assignment expression which has no error but it is not doing the update. Regards

  • Oracle 11G RAC 2 node

    Hi, I'm bringing up an Oracle 11.2.0- 2 node RAC setup on Oracle linux5. I have successfully installed Oracle clusterware files(11.2 grid infrastruture installation) and Oracle RAC DB on a 2 node cluster. I have installed all Clusterware files, DB fi