Problem with Runtime.getRuntime().exec

Hi ,
i'm using jBuilderX and windows 2000 server . My problem is that i can't
find why
in my code it doesn't work this:
import java.lang.*;
String command = new String("c:\\testd\\testf.bat"); // testf.bat -
batch file
Runtime.getRuntime().exec(command); // it doesn't
have any effect
Thanks in advance,

What's it supposed to do?
I can definitely help you on this 1, but I'd really like to see your streamoutputs. You can get these from the Process object that is created, but you'll need to add some threaded listeners to get the data.
Is this possible?

Similar Messages

  • Problems with Runtime.getRuntime().exec in Windows 2000

    Hello,
    I have a batch file that I want to run from my java application. My code is the following:
    try {
            Runtime.getRuntime().exec("cmd.exe /c C:\\temp\\shortcut.bat");
    } catch (Exception e) {
         System.out.println(e.getMessage());
    }I was developing on windows XP and it worked just fine. But then I tested it on windows 2000 and it didn't work. The batch file is okay, because if I run the batch file myself it works just fine, even from the command line. I get no errors what so ever, it just doesn't do anything...
    Can somebody help me with this?
    thx in advance

    thank you all so much
    I figured it out... It was a combination of two things that went wrong.
    First one: in my batch file I had:
    cd C:\tempwhich worsk fine in XP, but in it doesn't in 2000. In 2000 it has to be:
    C:
    cd \temp But just changing that wasn't enough, I also needed the "start"
    Now it works just fine on 2000, hopefully it'll still work on xp as well.
    THX!

  • Need help with Runtime.getRuntime().exec

    If there is a better place to post please let me know. I need some help understanding what is going on and was hoping someone might be able to provide some information. I would like to use Runtime.getRuntime().exec to copy a file in linux. Here is the code I am using:
    try {
    Process p = Runtime.getRuntime().exec("cp -v foo foo2");
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while ((line = in.readLine()) != null) {
    System.out.println(line);
    } catch (IOException e) {
    e.printStackTrace();
    If I use cp, with the System.out.println(line) I can see that it has copied and of course when I check the command line indeed it has. My problem is that I really need to use the dd command, but I can't see the output that dd displays. It copies the file just fine but I need the output. If someone can provide some explaination or help I would really appreciate it. Thanks.

    By default, dd sends its output to stdout, so any status messages it has go to stderr. Use getErrorStream (double check the docs for the method name) just like you're currently using getInputSTream.

  • Problems with Runtime.getRuntime().exe and getting output. Please Help me!!

    I'm creating a program that runs the followings programs written in C and compiled with gcc:
    ==========================The first C program====================================
    #include<stdio.h>
    void leia();
    main()
    int x = 20;
    int y = 2;
    printf( "Marcinho e Danny\n" );
    printf( "Te\n" );
    printf( "Vida\n" );
    printf( "Marciorja: %d.\n", x * y );
    ===============================================================================
    ==========================The second C program====================================
    #include<stdio.h>
    void leia();
    main()
    int x = 20;
    int y = 2;
    printf( "Marcinho e Danny\n" );
    printf( "Te\n" );
    printf( "Vida\n" );
    printf( "Marciorja: %d.\n", x * y );
    scanf( "%d", &x ); //This is the statement added to the latter C program.
    ===============================================================================
    I compiled this C program and generates the a.exe program. I have the following Java program:
    ==================================================================================
    import java.awt.Color;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.util.StringTokenizer;
    import javax.swing.JFrame;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.EditorKit;
    import javax.swing.text.MutableAttributeSet;
    import javax.swing.text.Style;
    import javax.swing.text.StyledDocument;
    import javax.swing.text.StyledEditorKit;
    public class Teste
    private BufferedWriter out;
    private BufferedReader in;
    private Style stylePrompt;
    private LeitorDeEntrada le;
    private String entrada = "";
    private AreaDeEdicao areaDeTexto;
    Process p = null;
    public Teste( AreaDeEdicao areaDeTexto )
    this.areaDeTexto = areaDeTexto;
    public void runCommand( String command ) throws IOException
    StringTokenizer strTokenizer = new StringTokenizer( command );
    String mainCommand = null;
    String argument = null;
    StyledDocument doc = areaDeTexto.getStyledDocument( );
    String[] prefix = new String[] { "cmd.exe", "/c", command };
    p = Runtime.getRuntime().exec( prefix, null, new File( System.getProperty( "user.dir" ) ) );
    in = new BufferedReader( new InputStreamReader( p.getInputStream( ) ) );
    out = new BufferedWriter( new OutputStreamWriter( p.getOutputStream( ) ) );
    out.flush();
    Thread t = new Thread( )
    public void run( )
    super.setName( "Marcio" );
    execute( );
    public void execute( )
    String c = null;
    try
    if( !in.ready( ) )
    try
    this.sleep( 1000 );
    catch( InterruptedException e2 )
    e2.printStackTrace( );
    System.out.println( "in.rea: " + in.ready( ) );
    c = in.readLine( );
    catch( IOException e )
    e.printStackTrace( );
    String str = "";
    while( c != null )
    str = c + "\n";
    try
    areaDeTexto.getDocument( ).insertString( areaDeTexto.getDocument( )
    .getLength( ),
    str, null );
    catch( BadLocationException e3 )
    e3.printStackTrace( );
    try
    c = in.readLine( );
    catch( IOException e2 )
    e2.printStackTrace( );
    areaDeTexto.setCaretPosition( areaDeTexto.getDocument( )
    .getLength( ) );
    try
    in.close( );
    catch( IOException e1 )
    e1.printStackTrace( );
    t.setDaemon( true );
    t.start( );
    le = new LeitorDeEntrada( );
    areaDeTexto.addKeyListener( le );
    public static void main( String[] args )
    JFrame janela = new JFrame( );
    AreaDeEdicao areaDeTexto = new AreaDeEdicao( new MyDocument( ) );
    areaDeTexto.setBackground( Color.black );
    areaDeTexto.setForeground( Color.GREEN );
    janela.getContentPane( ).add( areaDeTexto );
    Teste teste = new Teste( areaDeTexto );
    try
    teste.runCommand( "a.exe" );
    catch( IOException e )
    e.printStackTrace( );
    janela.setSize( 500, 300 );
    janela.setVisible( true );
    class LeitorDeEntrada extends KeyAdapter
    public void keyPressed( KeyEvent e )
    char c = e.getKeyChar( );
    System.out.println( "keyPressed" );
    try
    if( c == '\n' )
    areaDeTexto.getDocument().insertString( areaDeTexto.getDocument( )
    .getLength( ),
    c + "", null );
    out.write( c + "" );
    out.flush();
    catch( BadLocationException e2 )
    e2.printStackTrace( );
    } catch (IOException e2) {
    e2.printStackTrace();
    ==================================================================================
    This Java program is very simple. It runs the a.exe using the method Runtime.getRuntime().exec and gets input for a.exe from a JTextPane and shows the output in the same JTextPane.
    If my a.exe represents the binary code of the first C program the text in the JTextPane is the correct output of the a.exe. But, if my a.exe represents the binary code of the second C program, the JTextPane shows the messages ( "Marcinho e Danny\n", "Te\n", "Vida\n", "Marciorja: %d.\n") after I enter the value claimed by the scanf.
    I tested my Java program running programs that require input and all have the same behavior:.
    What can I need to do to solve this bug?
    I read other posts with the same problem and nobody answers what is the problem.
    I'LL pay 10 Duke dollars to the first that answers me.

    The second C program with the statement fflush( stdout ) produces the right output.
    #include<stdio.h>
    void leia();
    main()
    int x = 20;
    int y = 2;
    printf( "Marcinho e Danny\n" );
    printf( "Te\n" );
    printf( "Vida\n" );
    fflush( stdout ); //added statement.
    printf( "Marciorja: %d.\n", x * y );
    scanf( "%d", &x ); //This is the statement added to the latter C program.
    but what can I do to run C programs that doesn't flush the stdout?

  • Problems running Runtime.getRuntime().exec(path)

    I am trying to run the following command, so that i can execute a file on DOS
    Runtime.getRuntime().exec(path);
    where
    path = cmd /c C:\Dokumente und Einstellungen\Administrator\Lokale Einstellungen\Temp\muexec2562.bat
    (btw i think /c is german notoation used for -c). all i get is the DOS screen briefly popping up on screen and then disappearing. The .bat files contains commands to copy files.
    Thanks

    Replace your path with
    path = C:\Dokumente und Einstellungen\Administrator\Lokale Einstellungen\Temp\muexec2562.bat

  • Need help on changing directories with Runtime.getRuntime().exec() (shell)

    I want to create a perfect remote shell with Runtime.getRuntime(). I just can't get it to change directories. I want that if the remote user type "cd.." he changes the directory. At the moment, I can't get anything else than the "user.dir" directory.
    Is there anyway to send additionnal commands to cmd.exe after the Runtime.getRuntime().exec(). Because at the moment I'm running these commands:
    cmd[0] = "cmd.exe" ;
    cmd[1] = "/C" ;
    cmd[2] = commandString;
    After that I just wanna do stuff as if I really was at the computer and had a cmd.exe window open. I tried the output stream, I tried placing "&&" in front of the commandString(worked when I did it in cmd window), tried doing multiple Runtime.getRuntime().exec(). Starting to pull my hair out here.

    Because essentially I want this to be a remote shell.
    So I need it to accepts commands such as cd to change
    around the directory so the person can navigate the
    computer.
    I just managed to be able to do it in one command
    line. For example I would send "cd c:\downloads dir"
    to the server and it would work but I would really
    like to keep track of the working directory so the
    user wouldn't always have to change the directory.Then you don't Runtime.exec() once for each command the user types. You Runtime.exec() a shell once, and pass what the user types and the shell's responses via the in/out streams available from the Process class.

  • Problem in Runtime.getRuntime().exec

    Hi,
    I am trying to start the tomcat server through a java application.Before starting the server,i need to run a batch file for setting up some classpaths.I am able to run the batch file and start the server,but its opening the 2 windows.How do i suppress it?
    One more problem is how do i stop the server?
    Code is:
    import java.io.*;
    public class Test
    public static void main(String args[]) {
    try {
         Process p = Runtime.getRuntime().exec("cmd /c start C:\\soap.bat");     
         p.destroy();
         Process p1 = Runtime.getRuntime().exec("cmd /c start C:\\jakarta-tomcat-3.2.1\\bin\\startup");
         //p.waitFor();     
         Thread.sleep(10000);
         p1.destroy();     
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
    bw.write("1");
    bw.flush();
    String line;
    while ((line = br.readLine()) != null) {
    System.out.println(line);
    br.close();
    bw.close();
    System.out.println(p.exitValue());
    catch(Exception e) {
    System.out.println(e);
    I need the help as early as possible.
    pls cc reply to:[email protected]
    Thanks
    Anitha

    Soln. to your first prob:
    1) To have the other DOS window closed, click on the extreme left-top corner of that window. In the menu that drops down ,select properties.In the properties window make sure the 'close on Exit' check Box is checked. Apply the changes.
    2) To stop the server u need to call the shutdown.bat file in the tomcat\bin dir. If u want to do this thru java then call the shutdown.bat file from your Runtime.exec() method. Same as u did for the startup file
    Hope this helps.

  • Weird behaviour with Runtime.getRuntime.exec() attempting to start IE

    I have developed a sample scheduler that it a web page the user fill in and then create a process schedule by the Timer class. The process starts IE in order to automate data entry normally done by a user. The Java code run well but IE when start from the p = Runtime.getRuntime().exec() class freeze. Is anyone can tell if IE require special setting to run in background?
    Here the Java code but once again it work well but IE freeze and cause the forked process to hang.
    // The schedule task
    public void scheduleTask(Object o) throws ApplicationException {
    ScheduleBean sb = (ScheduleBean)o;
    try {
    Timer timer = new Timer(true);
    RunReslotting rr = new RunReslotting();
    timer.schedule(rr, sb.getSchedulingDate());
    catch(IllegalArgumentException iae) {
    throw new ApplicationException(iae.getMessage());
    catch(IllegalStateException ise) {
    throw new ApplicationException(ise.getMessage());
    public class RunReslotting extends TimerTask {
    protected RunReslotting() {
    public void run() {
    String[] cmdLineParam = transportProfile(2);
    cmdLineParam[0] = "location=" + wr.getLocation();
    cmdLineParam[1] = "loc_class=" + wr.getNewStrategy();
    forkProcess("runie.bat", cmdLineParam);
    private String[] transportProfile(int startAt) {
    envProf = System.getenv();
    profCmd = new String[envProf.size() + startAt];
    itr = envProf.entrySet().iterator();
    int i = startAt;
    while (itr.hasNext()) {
    entry = (Map.Entry)itr.next();
    profCmd[i] = (String)entry.getKey() + "=" + (String)entry.getValue();
    i++;
    return profCmd;
    private void forkProcess(String processName, String[] osParam) throws ApplicationException {
    // Lance un nouveau process
    p = null;
    int i=0;
    try {
    p = Runtime.getRuntime().exec(processName, osParam);
    // Vide les buffers du process pour eviter de geler
    mcError = new MessageCatcher(p.getErrorStream());
    mcOutput = new MessageCatcher(p.getInputStream());
    mcError.start();
    mcOutput.start();
    i = p.waitFor();
    if ( (i != 0) || (mcError.getMessage() != null) || (mcOutput.getMessage() != null) ) {
    System.err.println("*** Process failed RC:" + i + " *** ");
    if (mcOutput.getMessage() != null) {
    System.err.println("Output messages: " + mcOutput.getMessage());
    if (mcError.getMessage() != null) {
    System.err.println("Error messages: " + mcError.getMessage());
    throw new ApplicationException("*** Process failed *** ");
    catch(IOException ioe) {
    throw new ApplicationException(ioe.getMessage());
    catch(InterruptedException ie) {
    throw new ApplicationException(ie.getMessage());
    Any suggestion will be appreciate. I�m working on that scheduler for a while and i'm desperate
    Thanks
    Francis

    This starts IE for me, no problem
    String[] cmd = {"C:\\Program Files\\Internet Explorer\\iexplore.exe"};
    Runtime.getRuntime().exec(cmd);

  • Problem with Runtime and exec()

    I have been trying for some time and having no luck yet.
    I think i better put the code here to make it clear.
    public static void main(String[] args) throws Exception
    try {
    String line;
    Runtime rt = Runtime.getRuntime();
    String[] cmd = {
    "cmd.exe","/c", "c://PROGRA~1//Java//jdk1.5.0_05//bin//javac.exe", "c://Temp//Test.java"
    Process p = rt.exec(cmd);
    int exitVal = p.waitFor();
    System.out.println("Process exitValue: " + exitVal);
    System.out.println("Is it compiled");
    catch(IOException e) {
    System.err.println("Error on exec() method");
    e.printStackTrace();
    I am getting 1 as an exitVal, which is an erro obviously.
    Does anyone knows what could be going wrong there?

    Well, the file is just a .java class. It is not a package - it is just one class. And in nofrmal cicumstances i would compile and run that same class name. So i can not include any package.
    To be clear i would put the lines i have added here:
    public static void main(String args[]) throws Exception
            try {
                String line;
                Runtime rt = Runtime.getRuntime();
                String[] cmd = {
                    "cmd.exe","/c", "c://progra~1//Java//jdk1.5.0_05//bin//javac.exe", "c://Temp//Test1//MainTest.java"
                 String[] cmd2 = {
                    "cmd.exe","/c", "c://progra~1//Java//jdk1.5.0_05//bin//java.exe", "c://Temp//Test1//MainTest"
                Process p = rt.exec(cmd);
                Runtime rt2 = Runtime.getRuntime();
                p = rt2.exec(cmd2);
                BufferedReader input = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                String temp = "";
                while((temp = input.readLine()) != null) {
                    System.out.println(temp);
                input.close();I just copyied the method and sorry for not using code tag earlier.

  • Kill "runtime.getruntime().exec"-generated processes with control-c?

    Hi there,
    In my java program I create 2 processes with "runtime.getruntime().exec", but when I stop my java program pressing control-c these 2 processes remains running and I have to kill them using linux command "kill".
    How can I program my code in order to kill these 2 processes when stopping my java program with control-c?
    I tried next but it didn't work for me:
            try {
    final Process proc = Runtime.getRuntime().exec ( "java ControlCProblemDemo" );
    Runtime.getRuntime().addShutdownHook(
    new Thread(){
    public void run(){
    proc.destroy();
    while ( true );
    } catch( IOException ioe ) {
    System.err.println( ioe );
    }Thank you very much in advance.
    Josu&eacute;

    so are you saying proc.destroy() does nothing?
    are you sure it's getting executed?
    is there an error?
    too little info here

  • Syntax of Runtime.getRuntime().exec()

    i hava batch file command (genXML) in directory C:\update ,this command syntax is: genXML sourceFile resultFile outputDirectory
    how can I run the command with Runtime.getRuntime().exec() ?
    Thanks

    i hava batch file command (genXML) in directory
    C:\update ,this command syntax is: genXML sourceFile
    resultFile outputDirectory
    how can I run the command with
    Runtime.getRuntime().exec() ?
    Thanksuse the
    public Process exec(String[] cmdarray)
    version of exec as follows:
    where genProg is the path and name of your genXML program
    ie. genProg = "C:\\update\\genXML.exe"
    String[] cmd = {genProg, source, results, outputDir};

  • Runtime.getRuntime().exec problem with linux script.

    Hello,
    I try to start a script under Linux RedHat 9. This script must just create another file.
    I work with JDK 1.4.1_02b06.
    If I use the next command
    process = Runtime.getRuntime().exec("/temp/myScript.sh");
    This is not working. I script file is existing otherwise I receive an error. I don't understand why the script is not executed!
    I have check some other posts in this forum but I cannot find the solution.
    Thanks in advance for your help.
    Alain.

    Try running it with sh: Runtime.getRuntime().exec("sh /temp/myScript.sh");

  • Runtime.getRuntime().exec problems running with applet

    Hi,
    I am running the command
    Process prc = Runtime.getRuntime().exec("net config workstation");
    InputStream in = prc.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    line = br.readLine();
    When running from an application(/stand alone program) on Win-NT it runs fine. But when i include the same code in an Applet and try to run.
    It doesnt return any thing. I see the DOS-prompt open and close and i can also see the required output generated on the DOS prompt, but the program doesnt return any results(null) in the InputStream.
    I even tried to get the ErrorStream incase it is writing some error but it doesnt write anything.
    I tried running some other commands like (cmd.exe /c set) which were able to run on both application as well as from the applet.
    I have tried giving the "net config workstation" command in all flavors
         String[] cmd = new String[3];
         cmd[0] = "cmd.exe";
         cmd[1] = "/C";
         cmd[2] = "net config workstation";     
    And      
         String[] cmd = new String[3];
         cmd[0] = "net.exe";
         cmd[1] = "config";
         cmd[2] = "workstation";          
    AND
         String[] cmd = new String[5];
         cmd[0] = "cmd.exe";
         cmd[1] = "/C";
         cmd[2] = "net.exe";
         cmd[3] = "config";
         cmd[4] = "workstation";     
    AND giing the full path as
    C:\winnt\system32\net.exe config workstation
    But still it doesnt work.
    Can anybody please suggest what is the problem.Its Urgent.....
    Well the purpose of this is to get users system properties like the Logon Domain , server name etc.... or else can anybody suggest a better way to obtain this information.....
    Your reply will be highly appriciated...
    Thanks in Advance......

    Thanks for atleast replying.....
    Sorry, i forgot to mention.... yes OfCourse, i am using an Signed Applet..... That how i was able to run the "set" command.....
    I have made sure it is not sucha simple problem..... the thing is as i have mentioned i know that even "net config workstation" works..... cause i see the output on the DOS prompt,.... but this output is not returned to the Applet in the getInputStream()/getErrorStream().....
    Can anybody please suggest a way to get this output..... OR is there some other way to get the machine's domain, server name etc info from the machine....?????
    Thanks in Advance...!!

  • Runtime.getRuntime().exec problems

    i am trying to run files from my java application, i use the following command
    Runtime.getRuntime().exec("cmd /c start " + filePath);but it seems that it cant handle file path with spaces, like
    C:\Documents and Settings\Administrator\My Documents\My Web\Untitled-3.fla
    it works well with path like this
    C:\Downloads\1.rar
    am i right? and how to solve this problem? thanks

            final String[] command =
                "cmd.exe",
                "/C",
                "start \"" + filename + "\"",
            final Process p = Runtime.getRuntime().exec(command);this method can only trigger files in the same folder as the java application, isnt it?

  • Problem with runtime.exec().It hangs Up

    Hi all,
    I am having a problem with the runtime.exec method.I am trying to execute linux commands using this method.For most of the commands it works fine.But when i tried to change the user with the su command in linux my program hung up.So please help me to get around this.any help would be highly appreciable..
    I am pasting the code..
    <code>
    Process p=null;
    int ch=0;
    try
    System.out.println("Before executing command");
    String unlock_command="sh changeuser.sh";
    p = Runtime.getRuntime().exec(new String[] {"/bin/sh","-c","su tony"});
    InputStreamReader myIStreamReader = new InputStreamReader(p.getInputStream());
    while ((ch = myIStreamReader.read()) != -1)
    System.out.print((char)ch);
    p.waitFor();
    int p_exitvalue = p.exitValue();
    System.out.println("After executing the command and the exit value = "+p_exitvalue);
    p.destroy();
    catch (IOException anIOException)
    System.out.println(anIOException);
    catch(Exception e)
    e.printStackTrace();
    </code>
    Thanks
    HowRYou

    Hi sabre,
    What you have pointed out is right.But if i change the user as root then it will not ask for a password.Isn't it.Anyway thank you for giving your suggestions.Can yoiu help me more.Waiting for all of your help.I will try to swoitch between different users othere than root by giving the password.So just help me.

Maybe you are looking for