Runtime.exec() I need to run a command prompt command from java.

the code i have that doesn't seem to work is:
String driveloc = System.getProperty("user.dir").substring( 0, 1 );
        String path = jTextFieldPath.getText();
        String path2 = jTextFieldPath.getText().substring(0, jTextFieldPath.getText().length()-3) + "lst";
        String[] cmd = { "cmd.exe", "/" + driveloc, "ASMtools\\AS11 " + path + " -L >" + path2};
        txt_mf.append( cmd[3] );
        try {
            Process np = Runtime.getRuntime().exec( cmd );
        catch( java.io.IOException ioe) {
            //error
        }jTextFieldPath.getText() contains the path of the file saved by my program.
the line of code i am trying to run is:
AS11 FILE1 -L FILE2this line compiles the asm file and converts it to a lst creating an s19 file in the process. AS11 is an exe that aids the command prompt much like javac.
If you could help me figure this out it would be great.
Thanks in advance,
-Juke

String driveloc =
System.getProperty("user.dir").substring( 0, 1 );
String[] cmd = { "cmd.exe", "/" + driveloc,
  "ASMtools\\AS11 " + path + " -L >" + path2};Are you sure you want to invoke cmd.exe with the switch /c or /d or whatever depending on System.getProperty("user.dir") ?
Starts a new instance of the Windows 2000 command interpreter
CMD [A | /U] [Q] [D] [E:ON | /E:OFF] [F:ON | /F:OFF] [V:ON | /V:OFF]
    [[S] [C | /K] string]
/C      Carries out the command specified by string and then terminates
/K      Carries out the command specified by string but remains
/S      Modifies the treatment of string after /C or /K (see below)
/Q      Turns echo off
/D      Disable execution of AutoRun commands from registry (see below)
/A      Causes the output of internal commands to a pipe or file to be ANSI
/U      Causes the output of internal commands to a pipe or file to be
        Unicode
/T:fg   Sets the foreground/background colors (see COLOR /? for more info)
/E:ON   Enable command extensions (see below)
/E:OFF  Disable command extensions (see below)
/F:ON   Enable file and directory name completion characters (see below)
/F:OFF  Disable file and directory name completion characters (see below)
/V:ON   Enable delayed environment variable expansion using c as the
        delimiter. For example, /V:ON would allow !var! to expand the
        variable var at execution time.  The var syntax expands variables
        at input time, which is quite a different thing when inside of a FOR
        loop.
/V:OFF  Disable delayed environment expansion.

Similar Messages

  • Running command prompt externally from Java

    Hi,
    Does anyone know how to make a Java program that opens up the command prompt and runs certain commands? Thanks,
    Adam

    Read this before you use it:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • HT1926 iTunes won't install everything it needs to run.  I remove it from my computer and reinstall it and it keeps saying it.  I am using Windows 7 and the latest update from iTunes.

    iTunes won't install everything it needs to run.  I remove it from my computer and reinstall it and it keeps saying it.  I am using Windows 7 and the latest update from iTunes.

    What does the error message say when you install iTunes and it fails?
    This post was edited by Malignance

  • How java runs in command prompt and why java runs on it

    how java runs in command prompt and why java runs on it

    command prompt was used before the development of IDEs like RAD,eclipse etc.
    its still used for better understanding of the compilation and errors.
    type the java file and save the file(source file) in the bin folder of ur jdk environment with extension .java. the source file must be the one that has the main method declared.
    in the cmd prompt screen , set the path of bin folder.
    eg:C:/program files/jdk(some version)/bin/...
    for compilation,type:
    javac (source file_name).java and press enter
    for running the file:
    java source file_name

  • Launching command containing pipe from Java

    Hi,
    i have some troubles to launch a command containing pipe from java.
    I've tried to backslash the pipe but it still not work.
    Maybe someone has an idea about that :
    head -102050 /data/a_very_big_file | tail -5
    the idea is to get 5 lines in the middle of a very big file.
    To launch commands from java i use i think the classical way,
    something like :
    Process p = Runtime.getRuntime().exec(commande[0], this.envp, new File(this.pathExecution));
    I obtain this error :
    ERROR : head: invalid option -- 5
    ERROR : Try `head --help' for more information.
    Thanks for your help,
    kevin.

    kevleb wrote:
    yes same result...
    but i think the problem come from the fact
    that when you pipe your result of a command,
    you launch an other process (is that true).i don't know if another process is launched (the probability is rather high, though)
    but even if that's the case, from the time you rely on a shell and not directly on exec(), i think it shouldn't be a problem to include a | inside the command ; i don't have an idea why it gives you that message error :\

  • How to execute a Command Prompt command from J2SE code executing on Windows

    How to execute a Command Prompt command from J2SE code executing on Windows??
    Please help me

    [http://java.sun.com/docs/books/tutorial/getStarted/]
    ~

  • Runtime.exec help needed

    Hello,
    I am having a strange problem in using the Runtime.exec(command, null, workDirectory) method. Its giving an IOException and says:
    java.io.IOException: CreateProcess: delmembtrn-05.bat error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Win32Process.java:66)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:551)
    at java.lang.Runtime.exec(Runtime.java:418)
    at java.lang.Runtime.exec(Runtime.java:361)
    at java.lang.Runtime.exec(Runtime.java:325)
    Can anyone please guide me whats wrong here? I am trying to run a batch file which will run some java programs. I am running this program from one place and the batch file is in a different place(as represented by the workDir parameter in the exec method). This is holdin up my schedule. Someone can you please help me in this regard. Mail id: [email protected]

    I wanted to produce the same error before giving any advice - so i wrote:
    import java.lang.*;
    public class TestExec
         public static void main(String Arg[])
         throws Exception
              String command="go.bat";
              String envp [] = null;
              String workingDir="c:/temp/WorkingDir";
              Runtime.getRuntime().exec(command,envp,new java.io.File(workingDir) );
    }go.bat is not in path env var...
    I put go.bat into the workingDir and got this error:
    C:\TEMP\TestClass>java TestExec
    Exception in thread "main" java.io.IOException: CreateProcess: go.bat error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Unknown Source)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at TestExec.main(TestExec.java:13)
    Looks pretty similar!
    After changing "go.bat" to "c:/temp/workDir/go.bat" it worked without error...
    So the conclusion is
    that the bat file command string does not specify the right directory
    or
    the bat file is not in the path string
    The working dir parameter is not added to the path env var...
    Tim Smith
    IncWorx

  • How to run a command prompt " command " through java code

    hi all,
    There is a command
    "java -jar selenium-server.jar -interactive"
    which i am running through command prompt after going to D:\MyFolder\Examples .
    i want to execute this command using java code .please help

    This has already been answered in your other two threads on this topic - http://forum.java.sun.com/thread.jspa?threadID=5221221&messageID=9898287#9898287 and http://forum.java.sun.com/thread.jspa?threadID=5221223&messageID=9898290#9898290.
    For some reason you don't want to read the reference that tells you exactly how to do what you want and how to avoid the pitfalls - http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html .

  • How to run Executables or .bat files from Java?

    Hi!
    I need to open a Web Browser from Java App.
    Please, help me to do this without calling JNI
    -or-
    provide me with sample which works with
    Runtime.execute() method.
    I have done full permission:
    grant
         permission java.security.AllPermission "","";
    };Thank You in advance!

    To run any command from java code, the method is
    Runtime.getRuntime().exec( myCommandString )
    Where, myCommandString is something like "/full/pathname/command".
    If the pathname contains spaces, e.g. "c:\program files\windows\notepad", then enclose it in quotes within the quoted string. Or pre-tokenize them into elements of an array and call exec(String[] cmd) instead of exec(String cmd).
    From JDK1.3 there are two new overloaded Runtime.exec() methods. These allow you to specify starting directory for the child process.
    Note, there is a gotcha associated with reading output from commands. When the runtime exec's the process, it passes to it 3 streams, for stdin, stdout, and stderr; the out and err are buffered but the buffer size isn't very big. When your process runs, it reads (if needed) from in, and writes to out and err.
    If it doesn't write more than the buffer-size, it can run to completion.
    But if it tries to write more data to one or the other stream than the buffer can hold, the write blocks, and your process hangs, waiting for you to empty the buffer so it can write some more.
    So after the exec call, get the streams, and read from them in a loop until they both hit end-of-stream (don't block on either one, just read whatever is available from each, each loop iteration).
    Then when the streams have ended, call the process.waitFor() method to let it finish dying.
    Now, here is a code snippet how you achieve this.
    String strCommand = "cmd.exe /c " + strCommand;
    boolean bWait = true;
    //execute the command
    try
         Runtime r = Runtime.getRuntime();
         Process pr = r.exec(strCommand);
         Process pr = r.exec(callAndArgs);
         BufferedInputStream bis =new BufferedInputStream(pr.getInputStream ());
         int c=0;
         /** Outlet for IO for the process **/
         while (c!=-1)
              c=bis.read();
         /**Now wait for the process to get finished **/
         if(bWait == true)
              pr.waitFor();
              pr.destroy();
    catch(Exception e)
         System.out.println("Could not execute process " + strCommand);
         return(false);

  • Clear Command Line Console from Java

    Is there a way to clear the dos/shell console screen from a java program (the same way as cls would do in dos ir clear would do in unix) without making a Runtime.exec call??
    Thanks for your time
    wwe8

    What console window are you talking about?
    1- You might be starting a java application in a console window.
    2-Or it might be another console window.
    3-You might be starting a console window in java via Runtime.exec().
    For 1 and 2 you would need a JNI, platform specific solution. I believe the java testing tools do this, so if you got one of those it might provide an interface for this.
    If 3, then you would use the input stream to pass the command to the window.

  • Invoking command prompt & executing a java class from one more java class

    Hi,
    I have a problem with my application. I need to develop an editor which compiles and interpretes java programmes. I am develoopping it in Java (Swing and pure Java). I have no problem in compiling a java programme from my editor. But while execuing if any body writes a programme which has console input the system hangs. I am using Runtime.exec() method to call command prompt of Win'2000. My editor is working fine for the programmes written without console input in my editor. I want the same type of input acceptance as JCreator / Vim editors accept.
    How can i achieve this? Please give me some source code help for my requirement.

    When you create a Process object from executing a command you can grab it's input and output streams. Using these, and a text area, you can create a "virtual terminal" for your user to work with their console programs. The rest is just details :)

  • HOW DO I  RUN A UNIX BASH SCRIPT FROM JAVA??

    HI. Here's a tricky little problem i have. There's a unix bash script that has some commands in it, that manipulate a file. It appends a certain string variable to a file called users. The users file is an ordinary text file.
    I know this script to work perfectly, when i invoke it like this directyl from the command line: ./addusers.sh
    or even: bash /downloads/selinux/policy/addusers.sh
    Now, i have a java program, and its meant to just execute that script. It doesnt throw any Exceptions at runtime. But when i look at the users file, and expect it to have an extra line that was the string variable, the file is UNTOUCHED!
    Again, direct command line invocation works, but not from java. Here's what my invocation from java looks like:
    Process p = Runtime.getRunTime().exec("bash downloads/selinux/policy/addusers.sh");
    The strange thing is, i tried a different bash command. I tried:
    Process p = Runtime.getRunTime().exec("mkdir /temporary");
    and this worked!
    so why not the other one??
    I cant figure it out.

    You say:
    bash /downloads/selinux/policy/addusers.sh
    And you say in Java:
    Process p = Runtime.getRunTime().exec("bash
    downloads/selinux/policy/addusers.sh");
    As if a leading / would be missing from the Java
    version...nyix says:>
    ...OK sorry about that. i DO have a / in front of the downloads.... section in the java method. So its:
    Process p = Runtime.getRunTime().
    exec("bash /downloads/selinux/policy/addusers.sh");
    HELP please?

  • Need to access/connect Remote Unix server from Java

    Please any one give me a direct solution for connecting a remote Unix server through telnet connection from java application. Thanks in advance..

    If I run the below program codes, in the console it is asking to enter username and password in manual but I need to give it automatically.
    The highlighted "root" is entered by the user manually using keyboard.
    Expected:
    I mean the username, password and some action is set to be automatic, so that it should not ask the user to enter the input from keyboard.
    import java.awt.Robot;
    import java.awt.event.KeyEvent;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import org.apache.commons.net.telnet.TelnetClient;
    import org.apache.commons.net.telnet.TelnetNotificationHandler;
    import org.apache.commons.net.telnet.SimpleOptionHandler;
    import org.apache.commons.net.telnet.EchoOptionHandler;
    import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
    import org.apache.commons.net.telnet.SuppressGAOptionHandler;
    import org.apache.commons.net.telnet.InvalidTelnetOptionException;
    import java.util.StringTokenizer;
    * This is a simple example of use of TelnetClient.
    * An external option handler (SimpleTelnetOptionHandler) is used.
    * Initial configuration requested by TelnetClient will be:
    * WILL ECHO, WILL SUPPR
    * ESS-GA, DO SUPPRESS-GA.
    * VT100 terminal type will be subnegotiated.
    * <p>
    * Also, use of the sendAYT(), getLocalOptionState(), getRemoteOptionState()
    * is demonstrated.
    * When connected, type AYT to send an AYT command to the server and see
    * the result.
    * Type OPT to see a report of the state of the first 25 options.
    * <p>
    * @author Bruno D'Avanzo
    public class UnixConnect implements Runnable, TelnetNotificationHandler
        static TelnetClient tc = null;
         * Main for the TelnetClientExample.
        public static void main(String[] args) throws IOException
            FileOutputStream fout = null;
            /*if(args.length < 1)
                System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]");
                System.exit(1);
            String remoteip = "192.168.20.11";
            int remoteport;
            if (args.length > 1)
                remoteport = (new Integer(args[1])).intValue();
            else
                remoteport = 23;
            try
                fout = new FileOutputStream ("spy.log", true);
            catch (Exception e)
                System.err.println(
                    "Exception while opening the spy file: "
                    + e.getMessage());
            tc = new TelnetClient();
            TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT200", false, false, true, false);
            EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
            SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
            try
                tc.addOptionHandler(ttopt);
                tc.addOptionHandler(echoopt);
                tc.addOptionHandler(gaopt);
            catch (InvalidTelnetOptionException e)
                System.err.println("Error registering option handlers: " + e.getMessage());
            while (true)
                boolean end_loop = false;
                try
                    tc.connect(remoteip, remoteport);
                    Thread reader = new Thread (new UnixConnect());
                    tc.registerNotifHandler(new UnixConnect());
                    reader.start();
                    OutputStream outstr = tc.getOutputStream();
                    byte[] buff = new byte[1024];
                    int ret_read = 0;
                    do
                        try
                            ret_read = System.in.read(buff);
                            if(ret_read > 0)
                            outstr.write(buff, 0 , ret_read);
                            outstr.flush();
                        catch (Exception e)
                            System.err.println("Exception while reading keyboard:" + e.getMessage());
                            end_loop = true;
                    while((ret_read > 0) && (end_loop == false));
                    try
                        tc.disconnect();
                    catch (Exception e)
                              System.err.println("Exception while connecting:" + e.getMessage());
                catch (Exception e)
                        System.err.println("Exception while connecting:" + e.getMessage());
                        System.exit(1);
         * Callback method called when TelnetClient receives an option
         * negotiation command.
         * <p>
         * @param negotiation_code - type of negotiation command received
         * (RECEIVED_DO, RECEIVED_DONT, RECEIVED_WILL, RECEIVED_WONT)
         * <p>
         * @param option_code - code of the option negotiated
         * <p>
        public void receivedNegotiation(int negotiation_code, int option_code)
            String command = null;
            if(negotiation_code == TelnetNotificationHandler.RECEIVED_DO)
                command = "DO";
            else if(negotiation_code == TelnetNotificationHandler.RECEIVED_DONT)
                command = "DONT";
            else if(negotiation_code == TelnetNotificationHandler.RECEIVED_WILL)
                command = "WILL";
            else if(negotiation_code == TelnetNotificationHandler.RECEIVED_WONT)
                command = "WONT";
            System.out.println("Received " + command + " for option code " + option_code);
         * Reader thread.
         * Reads lines from the TelnetClient and echoes them
         * on the screen.
        public void run()
            InputStream instr = tc.getInputStream();
            try
                byte[] buff = new byte[1024];
                int ret_read = 0;
                do
                    ret_read = instr.read(buff);
                    if(ret_read > 0)
                       System.out.print(new String(buff, 0, ret_read));
                while (ret_read >= 0);
            catch (Exception e)
                System.err.println("Exception while reading socket:" + e.getMessage());
            try
                tc.disconnect();
            catch (Exception e)
                System.err.println("Exception while closing telnet:" + e.getMessage());

  • Command prompt issue from VBscript

    So I have this script that works perfectly for parsing out a COM number and then sending data to said COM port via the command line (things like 'ipconfig > //./COM15'). The issue is that it only works when I use the /K modifier which tells the command
    windows to stay open.  I don't want them to stay open, but whenever I remove the /K, it doesn't work. Nothing gets copied to the COM port. I suspect the cause of this is the command prompt closing before things like systeminfo can finish running. So is
    there a way to have the command prompt window stay open for a short amount of time and then close?
    'Part 1: FindCOM port
    fileName = "C:\rtlstuff\COM.txt"
    Set regex = New RegExp
    regex.Pattern = "COM(\d+)"
    regex.IgnoreCase = True
    regex.Global = True
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set file = fso.OpenTextFile(fileName)
    text = file.ReadAll()
    file.Close
    Dim ComPort
    Set matches = regex.Execute(text)
    For Each m In matches
    ComPort = m.SubMatches(0)
    Next
    'Part 2: Set file dictionary
    set oDic = CreateObject("Scripting.Dictionary")
    oDic.Add 0, "ECHO %DATE% %TIME% > //./COM"
    oDic.Add 1, "ipconfig > //./COM"
    oDic.Add 2, "systeminfo > //./COM"
    v = 3
    'Part 3: Set COM Variables
    Set oShell = WScript.CreateObject ("WScript.Shell")
    MODE = "MODE COM" & ComPort & " 9600,N,8,1,P"
    oShell.run "cmd.exe /C" & MODE
    'Part 4: Data transmission
    Dim Command
    x=0
    do while x < v
    Command = oDic.Item(x) & Comport
    msgbox Command
    oShell.run "cmd.exe " & Command
    x=x+1
    wscript.sleep 10000
    loop

    Can you help me with syntax? I'm still not hugely familiar with VB and I'm not sure how to set this up. This current iteration does not work.
    'Part 1: FindCOM port
    fileName = "C:\rtlstuff\COM.txt"
    Set regex = New RegExp
    regex.Pattern = "COM(\d+)"
    regex.IgnoreCase = True
    regex.Global = True
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set file = fso.OpenTextFile(fileName)
    text = file.ReadAll()
    file.Close
    Dim ComPort
    Set matches = regex.Execute(text)
    For Each m In matches
    ComPort = m.SubMatches(0)
    Next
    'Part 2: Set file dictionary
    set oDic = CreateObject("Scripting.Dictionary")
    oDic.Add 0, "ECHO %DATE% %TIME% > //./COM"
    oDic.Add 1, "ipconfig > //./COM"
    oDic.Add 2, "systeminfo > //./COM"
    v = 3
    'Part 3: Set COM Variables\par
    Set oShell = WScript.CreateObject ("WScript.Shell")
    MODE = "MODE COM" & ComPort & " 9600,N,8,1,P"
    oShell.run "cmd.exe /C" & MODE
    'Part 4: Data transmission
    Dim Command
    i = True
    x=0
    do while x < v
    Command = oDic.Item(x) & Comport
    msgbox Command
    oShell.run "cmd.exe " & Command , ,True
    x=x+1
    wscript.sleep 10000
    loop

  • Error running My Web Service Client From java

    Hi,
    I have developed and successfully compiled my webservice using the fromjava programming model that comes pre-packed with Jwsdp 2.0. I ran the sample/from java sucessfully and it rn okay. I also wrote a small weservice that just concatenated 2 strings and that worked well as also. However when I implemented more complex functionality in my IMPL clas i.e calling other classes in the IMPL's package and other imported packages, I get the error below when I run my client, which was built successfully.
    Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Unknown fault type:class java.lang.NoClassDefFoundError
    [java] at com.sun.xml.ws.encoding.soap.ClientEncoderDecoder.toMessageInfo(ClientEncoderDecoder.java:82).............
    I built both the server and the client with the ant tool e.g
    <install DIR>\Sun\jwsdp-2.0\apache-ant\bin\ant server
    <install DIR>\Sun\jwsdp-2.0\apache-ant\bin\ant client
    and then ran the client like below...
    <install DIR>\Sun\jwsdp-2.0\apache-ant\bin\ant run
    Please if anyone has encountered this problem or if you know the cause of this problem, please drop a note.
    Thanks
    Dennis

    I narrowed down the problem to the fact that from my webservices impl class, I am trying to call classes and libraries that perform tasks like database calls etc....
    I think that I am not adding these classes or libraries to the jaxws environment as I should. I have ploughed through the documentation, and I noticed the <classpath> tag under <wsimport> which I added to the build.xml file pointing to my specific classes and libraries. Doing this enabled me to build the server sucessfully. However at runtime it throws that NoClassDef exception. Can some one offer some tips on how I can get the my classes to be executed at run time...
    Thanks

Maybe you are looking for