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

Similar Messages

  • How to execute Linux command from Java app.

    Hi all,
    Could anyone show me how to execute Linux command from Java app. For example, I have the need to execute the "ls" command from my Java app (which is running on the Linux machine), how should I write the codes?
    Thanks a lot,

    You can use "built-in" shell commands, you just need to invoke the shell and tell it to run the command. See the -c switch in the man page for your shell. But, "ls" isn't built-in anyays.
    If you use exec, you will want to set the directory with the dir argument to exec, or add it to the command or cmdarray. See the API for the variants of java.lang.Runtime.exec(). (If you're invoking it repeatedly, you can most likely modify a cmdarray more efficiently than having exec() decompose your command).
    You will also definitely want to save the returned Process and read the output from it (possibly stderr too and get an exit status). See API for java.lang.Process. Here's an example
    java.io.BufferedReader br =
    new java.io.BufferedReader(new java.io.InputStreamReader(
    Runtime.getRuntime().exec ("/sbin/ifconfig ppp0").
    getInputStream()));
    while ((s = br.readLine()) != null) {...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • 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 run system commands from JAVA

    Hi Friends,
    How to run windows system commands from JAVA
    Runtime r=Runtime.getRuntime();
    r.exec("dir");
    Throwing following Exception
    CreateProcess :dir error=2
    Thanks in advance
    Hamsa

    Hi ,
    in Windows NT this is not possible, you can use the following :
    Runtime r=Runtime.getRuntime();
    StringBuffer sbuf = new StringBuffer();
    String dir = new String();
    java.lang.Process proc = r.exec("cmd /c dir");
    InputStream is = proc.getInputStream();
    int ch ;
    while((ch=is.read() ) != -1)
    sbuf.append((char)ch);
    is.close();
    dir = sbuf.toString();
    System.out.println(dir );

  • How to execute .msi files from java program

    Hi friends,
    i have written a java program which invokes and thereby execute any executable files like .exe and .bat.
    So its working fine with .exe and .bat files, but it is not working with .msi files.......can you please help me how can i execute .msi files as well??
    public class Executeexe {
         public static void main(String ar[])
              try
              Process p=null;
              Runtime rt=Runtime.getRuntime();
              p=rt.exec("D:\\mysql-essential-5.0.83-win32.msi");
              p.waitFor();
    catch(Exception e)
    }here is the program

    Make sure that the command that's being exec'd works from the cmd line.
    Then read this article and do what it says:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    Then if you still are having problems explain what "...it is not working with .msi files..." really means, and provide a [SSCCE Example program|http://mindprod.com/jgloss/sscce.html]

  • How to access system calls from java program?

    i am having a doubt regarding accessing system calls from a Java program like accessing unix system calls from a c program.

    Runtime.getRuntime().exec("line command here");
    example:
    Runtime.getRuntime().exec("ls -la");

  • 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

  • How to execute MySqlDump Command from java..........

    hi friends,Iam used mysqldump command in linux platform to take backup of the database,its work properly....the command am used is
    mysqldump -u root -p threadpool > sampledatabase.sql
    I need to execute the same command in java....?Anyone here to know how to do that....?Thanks in advance........

    Crosspost:
    http://forum.java.sun.com/thread.jspa?threadID=5185230&messageID=9721722#9721722
    http://forum.java.sun.com/thread.jspa?threadID=5185199&messageID=9721587#9721587
    Do not mess the forum.

  • Starting an executable system command from java

    I'm new to Java and i was wondering : is it possible to start an executable from Java under Windows? If so, how?
    Thanx

    There are only about 9 billion responses a day on how to do this. Use the search feature.

  • 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

  • Execute shell command from Java

    Hi all,
    I need some idea for executing shell script from Java programe.
    For example i have start.sh script in /tmp/start.sh  folder of unix server.
    I want to execute shell script from local java code.
    Any idea on this.

    Hi,
           Read the following articles/posts, maybe this could help you:
          How to execute shell command from Java
    Running system commands in Java applications | java exec example | alvinalexander.com
    Want to invoke a linux shell command from Java - Stack Overflow

  • Execute linux command from java

    I wanna execute linux command from java, bu the output has error:
    Return code = 1
    top: failed tty get
    The code as:
    import java.io.*;
    public class Execute {
         public static void main(String[] args) {
              try {
                   final Process process = Runtime.getRuntime().exec("top");
                   new Thread() {
                        public void run() {
                             try {
                                  InputStream is = process.getInputStream();
                                  byte[] buffer = new byte[1024];
                                  for (int count = 0; (count = is.read(buffer)) >= 0;) {
                                       System.out.write(buffer, 0, count);
                             } catch (Exception e) {
                                  e.printStackTrace();
                   }.start();
                   new Thread() {
                        public void run() {
                             try {
                                  InputStream is = process.getErrorStream();
                                  byte[] buffer = new byte[1024];
                                  for (int count = 0; (count = is.read(buffer)) >= 0;) {
                                       System.err.write(buffer, 0, count);
                             } catch (Exception e) {
                                  e.printStackTrace();
                   }.start();
                   int returnCode = process.waitFor();
                   System.out.println("Return code = " + returnCode);
              } catch (Exception e) {
                   e.printStackTrace();
    }Help please.

    Your code is probably good to run a program, that does not use terminal capabilities.
    Program "top" is a little bit more complicated - you have to run it with a real terminal.
    Try to run "xterm -e top". You can find an example how to run an external program
    from java code in cnd/gdb module on http://cnd.netbeans.org
    For example, take a look at openExternalProgramIOWindow() method on this page:
    http://cnd.netbeans.org/source/browse/cnd/gdb/src/org/netbeans/modules/cnd/debugger/gdb/proxy/Attic/GdbProxyCL.java?rev=1.1.2.6.2.5&only_with_tag=release551_fixes&view=markup
    It runs a command with external terminal.
    Thanks,
    Nik

  • Unable to execute Linux command from Java

    Hi,
    I am currently working on a code wherein i need to execute Linux command from Java. Below are some of the query i have.
    1) Is there any efficient method of running OS commands from Java, rather than using Runtime and Process method.
    2) Below is details of my code which fails in execution
    **-- Java Version**
    java version "1.6.0"
    OpenJDK Runtime Environment (build 1.6.0-b09)
    OpenJDK Server VM (build 1.6.0-b09, mixed mode)
    -- Program Code ----
    Where <path> = Path i put myself
    package test;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.*;
    public class GetInode{
         * @param args
         public static void main(String[] args) {
              GetInode test = new GetInode();
              test.getInode();
         public void getInode(){                    
              String command = "/usr/bin/stat -Lt <path>;
              System.out.println(command);
              Process process;
              Runtime rt;     
              try{
              rt = Runtime.getRuntime();               
              process = rt.exec(command);
              InputStreamReader isr = new InputStreamReader(process.getErrorStream());
              BufferedReader bre = new BufferedReader(isr);
              BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream());
              System.out.println(bre.readLine());
    System.out.println(br.readLine().split(" ")[7]);
              process.destroy();          
              }catch (Exception ex){
                   System.out.println("Error :- " + ex.getMessage());
    ------Output -------------
    /usr/bin/stat -Lt "<path>"
    /usr/bin/stat: cannot stat `"<path>"': No such file or directory
    Error :- null
    Can any one help me what is wrong and why i am unable to run the Linux command from Java.

    For clarity purpose............i m submitting actual code here
    --- Code ---
    package test;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.*;
    public class GetInode{
    * @param args
    public static void main(String[] args) {
    GetInode test = new GetInode();
    test.getInode();
    public void getInode(){               
    String command = "/usr/bin/stat -Lt \"/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt\"";
    System.out.println(command);
    Process process;
    Runtime rt;
    try{
    rt = Runtime.getRuntime();
    process = rt.exec(command);
    InputStreamReader isr = new InputStreamReader(process.getErrorStream());
    BufferedReader bre = new BufferedReader(isr);
    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
    System.out.println(bre.readLine());
    System.out.println(br.readLine().split(" ")[7]);
    process.destroy();
    }catch (Exception ex){
    System.out.println("Error :- " + ex.getMessage());
    --- Output ---
    [ratz]s0898671: java GetInode
    /usr/bin/stat -Lt "/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt"
    /usr/bin/stat: cannot stat `"/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt"': No such file or directory
    Error :- null
    -- Linux Terminal --
    If i copy the first line from the output and execute on Linux terminal her is the output that i get
    [ratz]s0898671: /usr/bin/stat -Lt "/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt"
    /afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt 12003 24 81a4 453166 10000 1c 360466554 2 0 1 1246638450 1246638450 1246638450 4096
    Can you just assist me where am i really making mistake.......i was wondering if the command that i pass from Java....can be executed on Linux terminal why is it faling to run from java.........and when i print the Error Stream for process output........it show cannot Stat.......

  • How to call gnuplot command from java

    Hi there,
    In our course, we are required to develop an GUI for gnuplot. In case you don't know about gnuplot, it's a plotting program and has lots of command. We want to use java and swing, but now we don't know how to call gnuplot command from java, or how to execute a shell command(script) from java.
    By the way, since we need read in files with several columns of data and allow user to select a column, we want to use JTable. Is that reasonable?
    Thanks a lot for any suggestions!
    Jack

    Hi, there:
    Will using JTable add much overhead? I may have to use several JTables and switch among them. I can add scroll bar to or edit JTables, right?
    BTW, do you have experience about gnuplot? Can I find the command tree of gnuplot somewhere? Or do you know a better place to post question about gnuplot? unix/linux group, maybe.
    Thanks,
    Jack
    P.S. Would you guys answer my question after I use up my duke dollars? :- )

  • How to read system eventlog using java program in windows?

    How to read system eventlog using java program in windows?
    is there any java class available to do this ? or any one having sample code for this?
    Your friend Zoe

    Hi,
    There is no java class for reading event log in windows, so we can do one thing we can use windows system 32 VBS script to read the system log .
    The output of this command can be read using java program....
    we can use java exec for executing this system32 vbs script.
    use the below program and pass the command "eventquery"
    plz refer cscript,wscript
    import java.io.*;
    public class CmdExec {
    public static void main(String argv[]) {
    try {
    String line;
    Process p = Runtime.getRuntime().exec("Command");
    BufferedReader input =
    new BufferedReader
    (new InputStreamReader(p.getInputStream()));
    while ((line = input.readLine()) != null) {
    System.out.println(line);
    input.close();
    catch (Exception err) {
    err.printStackTrace();
    This sample program will list all the system log information....
    Zoe

Maybe you are looking for

  • Is it 3D graphic in apple commercials??

    Hello I recently read the article about shooting commercials of apple product. http://www.theverge.com/2013/5/8/4311868/the-illusion-of-simplicity-photographer -peter-belanger-on-shooting Surprisingly, photos of commercials or homepage are not just a

  • Should I close my 2 oldest CCs?

    Here's my rebuild since my 1/31/2011 BK7 discharge: (Card/Date Opened/CLBest Buy Rewards MC 10/14/2011 2,000 Merrick Bank Visa 12/1/2011 3,100 Barclays Rewards MC 4/10/2012 3,000 (Was $5700 CL, moved $2700 to NFL) Cap One Rewards Visa 10/1/2014 10,00

  • Expansion card for Zire 31+ the file pdb.

    Dear Madam/Sir. I own a palm one handheld Zire 31 and I purchase an SD expansion card of 2.0 GB witch should fit, but my handheld does not recognize the card, what should I do? my second question is it necessary to download the file with the pdb suff

  • Determine in which page an iView is embedded at runtime

    Hi, is it possible for an iView to find out in which page it is activated at runtime. I would like my iView to show different information for different pages where it is embedded. Regards Edmund

  • Security Filter Error

    Hi When i refresh my security filter i am getting an error saying cache size limit reached. can anybody tell me wer do i adjust my security filter chache size Thanks Abe Edited by: user11884591 on Sep 10, 2009 11:21 AM