Runtime.exec hangs even If I drain output.

Hi Everyone,
I'm trying to make a program that would give me access to a command line on a remote server. So what I'm trying to do is use Runtime.exec("cmd") to open a command line, then reading from it and printing to it normally.
The problem is the same very common problem anyone using exec encounters: it hangs. The thing is, however, I do drain the input and error streams immediately, but it still hangs, and here's a curious thing:
When I use a BufferedReader and use its readLine() method, it only manages to read the first two lines before it hangs, giving me an output such as this:
+Microsoft Windows XP [Version 5.1.2600]+
+(C) Copyright 1985-2001 Microsoft Corp.+
Of course I placed the System.out.println inside the loop that reads lines, cause if I put it outside the loop, I don't get any output at all because the subprocess hangs before the loop is finished.
Now if I don't use a buffer, and use the input's stream's read() method, it reads all the way through the output, but hangs at the end where it's supposed to read -1, and never reads it.
I thought maybe I could bypass that, and break the loop at the last character in the output (the character '>'). Now while this works the first time, sending the output to the client like this:
+Microsoft Windows XP [Version 5.1.2600]+
+(C) Copyright 1985-2001 Microsoft Corp.+
F:\eclipse workspace\RemCommand>
However it doesn't work after that, when I try to type any command. I send my command to the subprocess normally using a PrintWriter, and then try to read the output, but that fails because apparently the subprocess is still stuck at the -1 from the previous read operation.
I really don't know what the problem is, is it possible that the read possibly doesn't return -1 at all, maybe returns a different character to signify the end or something, and my loop keeps trying to read or what?
I'm at my wits end.
Any help?
Thanks in advance.

Here is the code again. Check the somehow improved detection of the default Windows prompt.
Check the lines in comments that allow you to define your own, perhaps more reliable prompt.
import java.io.*;
import java.util.*;
public class Cmd
  public static void main( String[] args ) throws Exception
    ProcessBuilder pb = new ProcessBuilder( "cmd" );
//    Map<String, String> env = pb.environment();
//    env.put( "PROMPT", ".,.,." );
    pb.redirectErrorStream( true );
    Process p = pb.start();
    InputStream is = p.getInputStream();
    OutputStream os = p.getOutputStream();
    PrintWriter pw = new PrintWriter( os, true );
    readToPrompt( is );
    pw.println( "dir" );
    readToPrompt( is );
    pw.println( "ipconfig" );
    readToPrompt( is );
    pw.println( "netstat" );
    readToPrompt( is );
  private static void readToPrompt( InputStream is ) throws IOException
    String s = "";
    for (;;)
      int i = is.read();
      if ( i < 0 )
        System.out.println();
        System.out.println( "EOF" );
        System.exit( 0 );
      s += new String( new byte[] { ( byte )i } ).charAt( 0 );
      if ( s.endsWith( "\r\n" ) )
        System.out.print( s );
        s = "";
//      if ( s.equals( ".,.,." ) )
      if ( s.length() > 2 && s.charAt( 0 ) >= 'A' && s.charAt( 0 ) <= 'Z' && s.charAt( 1 ) == ':' && s.endsWith( ">" ) )
        System.out.print( s );
        break;
}Edited by: baftos on Sep 10, 2008 11:27 AM

Similar Messages

  • Runtime.exec - hangs or doesn't produce output

    Hey,
    I've been trying to get my program to run an application that I downloaded off the net. It is a console based telnet application build for windows. Now, I've been trying to bascially automate some telnet stuff but it doesn't seem to work at the moment that is it doesn't give me output and it causes my computer to slow down. I've noticed that it does start the application which causes the slow down but I was wondering why it doesn't give me any output. Here is the code that I have
    import java.io.*;
    public class Main
      public static void main(String[] args)
        String command = new String[3];
        command[0] = "cmd.exe";
        command[1] = "/C";
        command[2] = "D:\\Temp\\telnet\telnet.exe";
        try
          Process p = Runtime.getRuntime().exec(command);
          BufferdReader stdin = new BufferedReader(new InputStreamReader
                                                   (p.getInputStream()));
          BufferedReader stderr = new BufferedRader(new InputStreamReader
                                                   (p.getErrorStream()));
          PrintStream stdout = new PrintStream(p.getOutputStream());
          String line = "";
          while((line = stderr.readLine()) != null)
            System.out.println(line);
          System.out.println();
          while((line = stdin.readLine()) != null)
            System.out.println(line);
          p.destroy();
        catch(Exception ex)
          System.out.println("Exception: " + ex.getMessage());
          System.exit(-1);
    }Could some please help me and trying to get this program to work?
    Thanks,
    Ny

    now try it
    you should get
    D:\Temp\telnet' is not recognized as an internal or external command,
    operable program or batch file.
    as an output
    import java.io.*;
    public class Main{
      public static void main(String[] args)
        String[] command = new String[3];
        command[0] = "cmd.exe";
        command[1] = "/C";
        command[2] = "D:\\Temp\\telnet\telnet.exe";
        try
          Process p = Runtime.getRuntime().exec(command);
          BufferedReader stdin = new BufferedReader(new InputStreamReader
                                                   (p.getInputStream()));
          BufferedReader stderr = new BufferedReader(new InputStreamReader
                                                   (p.getErrorStream()));
          PrintStream stdout = new PrintStream(p.getOutputStream());
          String line = "";
          while((line = stderr.readLine()) != null)
            System.out.println(line);
          System.out.println();
          while((line = stdin.readLine()) != null)
            System.out.println(line);
          p.destroy();
        catch(Exception ex)
          System.out.println("Exception: " + ex.getMessage());
          System.exit(-1);
    }

  • Running java process in a while loop using Runtime.exec() hangs on solaris

    I'm writting a multithreaded application in which I'll be starting multiple instances of "AppStartThread" class (given below). If I start only one instance of "AppStartThread", it is working fine. But if I start more than one instance of "AppStartThread", one of the threads hangs after some time (occasionaly). But other threads are working fine.
    I have the following questions:
    1. Is there any problem with starting a Thread inside another thread?. Here I'm executing the process in a while loop.
    2. Other thing i noticed is the Thread is hanging after completing the process ("java ExecuteProcess"). But the P.waitFor() is not coming out.
    3. Is it bcoz of the same problem as given in Bug ID : 4098442 ?.
    4. Also java 1.2.2 documentation says:
    "Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock. "
    I'm running this on sun Solaris/java 1.2.2 standard edition. If any of you have experienced the same problem please help me out.
    Will the same problem can happen on java 1.2.2 enterprise edition.?
    class AppStartThread implements Runnable
    public void run()
    while(true)
    try
    Process P=Runtime.getRuntime().exec("java ExecuteProcess");
    P.waitFor();
    System.out.println("after executing application.");
    P.destroy();
    P = null;
    System.gc();
    catch(java.io.IOException io)
    System.out.println("Could not execute application - IOException " + io);
    catch(java.lang.InterruptedException ip)
    System.out.println("Could not execute application - InterruptedException" + ip);
    catch (Exception e)
    System.out.println("Could not execute application -" + e.getMessage());

    I'm writting a multithreaded application in which I'll
    be starting multiple instances of "AppStartThread"
    class (given below). If I start only one instance of
    "AppStartThread", it is working fine. But if I start
    more than one instance of "AppStartThread", one of the
    threads hangs after some time (occasionaly). But other
    threads are working fine.
    I have the following questions:
    1. Is there any problem with starting a Thread inside
    another thread?. Here I'm executing the process in a
    while loop.Of course this is OK, as your code is always being run by one thread or another. And no, it doesn't depend on which thread is starting threads.
    2. Other thing i noticed is the Thread is hanging
    after completing the process ("java ExecuteProcess").
    But the P.waitFor() is not coming out.This is a vital clue. Is the process started by the Runtime.exec() actually completing or does the ps command still show that it is running?
    3. Is it bcoz of the same problem as given in Bug ID :
    4098442 ?.
    4. Also java 1.2.2 documentation says:
    "Because some native platforms only provide limited
    ed buffer size for standard input and output streams,
    failure to promptly write the input stream or read the
    output stream of the subprocess may cause the
    subprocess to block, and even deadlock. "These two are really the same thing (4098442 is not really a bug due to the reasons explained in the doc). If the program that you are exec'ing produces very much output, it is possible that the buffers to stdout and stderr are filling preventing your program from continuing. On Windows platforms, this buffer size is quite small (hundreds of characters) while (if I recall) on Solaris it is somewhat larger. However, I have seent his behavior causing problem on Solaris 8 in my own systems.
    I once hit this problem when I was 'sure' that I was emitting no output due to an exception being thrown that I wasn't even aware of - the stack trace was more than enough to fill the output buffer and cause the deadlock.
    You have several options. One, you could replace the System.out and System.err with PrintStream's backed up by (ie. on top of) BufferedOutputStream's that have large buffers (multi-K) that in turn are backed up by the original out and err PrintStream's. You would use System.setErr() and System.setOut() very early (static initializer block) in the startup of your class. The problem is that you are still at the mercy of code that may call flush() on these streams. I suppose you could implement your own FilterOutputStream to eat any flush requests...
    Another solution if you just don't care about the output is to replace System.out and System.err with PrintStreams that write to /dev/nul. This is really easy and efficient.
    The other tried and true approach is to start two threads in the main process each time you start a process. These will simply consume anything that is emitted through the stdout and stderr pipes. These would die when the streams close (i.e. when the process exits). Not pretty, but it works. I'd be worried about the overhead of two additional threads per external process except that processes have such huge overhead (considering you are starting a JVM) that it just won't matter. And it's not like the CPU is going to get hit much.
    If you do this frequently in your program you might consider using a worker thread pool (see Doug Lea's Executor class) to avoid creating a lot of fairly short-lived threads. But this is probably over-optimizing.
    Chuck

  • Runtime.exec() hangs with 1.4.1

    Hello altogether,
    I am trying to execute a command with Runtime.getRuntime.exec()
    I have already taken care of capturing the output and I observe that depending of the program I try to execute the process hangs.
    I am using JRE 1.4.1_02 under Redhat 7.2 with kernel 2.4.18-26
    Executing the same program under JRE 1.3.1 the program does not hang.
    Executing 'top -bn0q' hangs, executing 'ls -als' it hangs.
    Here is my sample code:
    <code>
    import java.io.*;
    public class Exec
    /** catches the output in a parallel thread */
    class StreamReader extends Thread
    String category = null;
    InputStream is;
    StreamReader(String category, InputStream is)
    this.category = category;
    this.is = is;
    public void run()
    try
    System.out.println(this.category+": reader runs");
    InputStreamReader isr = new InputStreamReader(this.is);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    while (br.ready() && (line = br.readLine())!=null)
    System.out.println(this.category+':'+line);
    catch (Exception e)
    e.printStackTrace();
    public void run(String[] cmd)
    StringBuffer outStrBuf = new StringBuffer();
    try
    Runtime rt = Runtime.getRuntime();
    System.out.println("got runtime");
    Process process = rt.exec(cmd);
    System.out.println("fired cmd");
    // any errors
    System.out.println("prepare error stream");
    StreamReader errSr = new StreamReader("ERR",process.getErrorStream());
    // any output
    System.out.println("prepare output stream");
    StreamReader outSr = new StreamReader("OUT",process.getInputStream());
    // start the readers to read
    System.out.println("start readers");
    errSr.start();
    outSr.start();
    System.out.println("waiting for process to end");
    process.waitFor(); //Waits for the subprocess to complete.
    catch (Exception e)
    System.err.println("Error while executing cmd: " + cmd);
    e.printStackTrace();
    System.out.println(outStrBuf);
         public static void main(String[] args)
    String [] cmd = {"top","-bn0q"};
    if (args.length >= 1)
    cmd = args;
    System.out.println(args[0]);
    Exec exec = new Exec();
    exec.run(cmd);
    </code>
    The output of java Exec is:
    [user]$ java Exec
    got runtime
    fired cmd
    prepare error stream
    prepare output stream
    start readers
    waiting for process to end
    OUT: reader runs
    ERR: reader runs
    ...and there it hangs. Interesting is, that when I use ls -als as command, I get the directory listing.
    Do you have any ideas what I am doing wrong? Is there any difference in the Runtime.exec() between 1.3 and 1.4 version?

    Unbelievable and what a shame. I was hacking 2 days on several variations of this problem and the solution and I finally found one difference:
    while (br.ready() && (line = br.readLine())!=null)
    I assume that when executing the command, the output streams are not ready and my Output gobbler threads end.
    ...however the command is still executing and starts to write its output. And as we all know this will overflow the buffer and the process hangs.
    So the final solution is:
    /** catches the output in a parallel thread */
    class StreamReader extends Thread
      String category = null;
      InputStream is;
      StreamReader(String category, InputStream is)
        this.category = category;
        this.is = is;
      public void run()
        try
          System.out.println(this.category+": reader runs");
          InputStreamReader isr = new InputStreamReader(this.is);
          BufferedReader br = new BufferedReader(isr);
          String line = null;
          while (/**br.ready() &&*/ (line = br.readLine())!=null)
            System.out.println(this.category+':'+line);
        catch (Exception e)
          e.printStackTrace();
    }So the only question that I have open: Why does this makes no problem with 1.3 but with 1.4 ?

  • Runtime.exec hang

    I used Runtime class to run a 3rd party exe. If I just called
    Runtime.exec("3rd.exe whatever"), 3rd.exe would run half way
    then hang. If I called Runtime.exec("start 3rd.exe whatever"),
    3rd.exe would run successfully. However, Runtime.getInputStream
    couldn't receive the output from 3rd.exe.
    Is any way I can get the output from 3rd.exe with "start 3rd.exe
    whatever"?

    Hi,KellanMom :
    I also experienced this problem.
    You should read sth from Process's inputStream,
    outputStream and errorStream.
    You can browse "http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html" to get details.
    Regards.
    Sunway

  • Runtime.exec() hangs on solaris 10, deadlock in soft_delete_session ?

    Hi,
    In my application sometimes Runtime.exec calls hangs for ever.
    The pstack of java process is at the end of the post. It seems like there is a deadlock in soft_delete_session.
    Does anyone know of any java/os patch we can apply to fix this issue?
    I will really appreciate any tips to get over this issue.
    # uname -a
    SunOS thor256 5.10 Generic_120011-14 sun4u sparc SUNW,Sun-Fire-V245
    # /opt/VRTSjre/jre1.5/bin/java -version
    java version "1.5.0_10"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_10-b03)
    Java HotSpot(TM) Server VM (build 1.5.0_10-b03, mixed mode)
    The trace is as follows:
    0xff340408 __lwp_park + 0x10
    0xff339068 mutex_lock_internal + 0x5d0
    0xfb08a2ec soft_delete_session + 0xf0
    0xfb089f90 soft_delete_all_sessions + 0x4c
    0xfb084348 finalize_common + 0x70
    0xfb0844d8 softtoken_fini + 0x44
    0xfb0d8d48 _fini + 0x4
    0xff3c00d0 call_fini + 0xc8
    0xff3ca614 remove_hdl + 0xab8
    0xff3c4d54 dlclose_intn + 0x98
    0xff3c4e68 dlclose + 0x5c
    0xfb3a2b3c pkcs11_slottable_delete + 0x138
    0xfb39d664 pkcs11_fini + 0x4c
    0xff2c0ea0 postforkchild_handler + 0x30
    0xff332c20 fork + 0x140
    0xfe8f8df4 Java_java_lang_UNIXProcess_forkAndExec + 0x7d4
    0xf9226020 0xf9226020 * java.lang.UNIXProcess.forkAndExec(byte[], byte[], int, byte[], int, byte[], boolean, java.io.FileDescriptor, java.io.FileDescriptor, java.io.FileDescriptor) bci:0 (Compiled frame; information may be imprecise)
    0xf92216c4 0xf92216c4 * java.lang.UNIXProcess.(byte[], byte[], int, byte[], int, byte[], boolean) bci:62 line:53 (Compiled frame)
    0xf90fa6b8 0xf90fa6b8 * java.lang.ProcessImpl.start(java.lang.String[], java.util.Map, java.lang.String, boolean) bci:182 line:65 (Compiled frame)
    0xf90fbe0c 0xf90fbe0c * java.lang.ProcessBuilder.start() bci:112 line:451 (Compiled frame)
    0xf921842c 0xf921842c * java.lang.Runtime.exec(java.lang.String[], java.lang.String[], java.io.File) bci:16 line:591 (Compiled frame)
    0xf9005874 * java.lang.Runtime.exec(java.lang.String[]) bci:4 line:464 (Interpreted frame)
    0xf9005874 * TestExec.run() bci:26 line:22 (Interpreted frame)
    0xf9005c2c * java.lang.Thread.run() bci:11 line:595 (Interpreted frame)
    0xf9000218
    0xfecdca88 void JavaCalls::call_helper(JavaValue*,methodHandle*,JavaCallArguments*,Thread*) + 0x5b8
    0xfecf4310 void JavaCalls::call_virtual(JavaValue*,Handle,KlassHandle,symbolHandle,symbolHandle ,Thread*) + 0x18c
    0xfecf416c void thread_entry(JavaThread*,Thread*) + 0x12c
    0xfecf3ff0 void JavaThread::run() + 0x1f4
    0xff02fb30 void*_start(void*) + 0x200
    0xff340368 lwpstart

    Found this information about this problem:
    Bug: http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=6276483
    Info for patch 127111-11: http://sunsolve.sun.com/search/document.do?assetkey=1-21-127111-11-1
    Download page: http://sunsolve.sun.com/show.do?target=patches/zos-s10

  • Runtime.exec() hangs

    When i am trying to execute a particular dos program from my java program, the system hangs. I am not even trying to retrieve any output from the program in my java code. Executing the same program from the dos shell doesn't cause any problems.
    I am running on Win98 --- hitting CTRL-ALT-DEL tells me that "winoldap" is NOT RESPONDING ---- i don't know what this is (atleast not the name of the program i am executing)
    PLEASE HELP.

    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • The Runtime.exec methods doesn't work well on Solaris ???

    I have two threads and I set the different running time.
    I use Runtime.exec to a run the command and use Process to get the process.
    It works properly in the windows2000 platform.
    However, when I transfer the platform to Solaris...and run the program...
    Two threads always at the same time....It is very wired....I always debug
    for 2 days....
    (at first I run "vmstat 1 2" command, later I change to "ls","rmdir"....etc,
    all of them don't work.....
    If I close the Runtime.exec..........Everything works well......)
    And I study the API. I found this message...
    The Runtime.exec methods may not work well for special processes on certain
    native platforms, such as native windowing processes, daemon processes,
    Win16/DOS processes on Win32, or shell scripts. The created subprocess does
    not have its own terminal or console.
    Could someone share her/his experience.....:(
    And if any other way I can run command inside java code instead of
    Runtime.exec.....???
    Please reply my mail to [email protected] I do appreciate your kindly &
    great help!!!!!!!!
    This is my code.......
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    * <p>ServerThread1</p>
    * <p>??�X???��?�D???�X???, "Vmstat 1 2".</p>
    class ServerThread1 extends Thread{
    private ServerAgent Sa;
    public ServerThread1 (String Name, ServerAgent Sa){
    super(Name);
    this.Sa = Sa; file://Assign ServerAgent reference Sa
    public void run(){
    while(true){
    try{
    Thread.sleep(5000);
    catch (Exception e){
    System.out.println("ServerThread1 fails");
    System.out.println("Thread1 is running.");
    try {
    Runtime rt1 = Runtime.getRuntime();
    Process proc1 = rt1.exec("mkdir"); ------>If I close
    rt1.exec , two threads works seperately...........:(
    catch (Exception e) {
    System.out.println("Thread1 Error");
    class ServerThread2 extends Thread{
    private ServerAgent Sa;
    public ServerThread2 (String Name, ServerAgent Sa){
    super(Name);
    this.Sa = Sa;
    public void run(){
    while(true){
    try{
    Thread.sleep(15000);
    catch (Exception e){
    System.out.println("ServerThread2 fails");
    System.out.println("Thread2 is running.");
    try {
    Runtime rt2 = Runtime.getRuntime();
    Process proc2 = rt2.exec("vmstat 1 2"); ----->If I don't run
    the rt2.exe, two threads work seperately....
    catch (Exception e) {
    System.out.println("Thread2 Error");
    public class ServerAgent{
    private Vector v1 = new Vector();
    private Vector v2 = new Vector();
    private Hashtable currentData = new Hashtable();
    private static String startUpSwap = null;
    private static String startUpMem = null;
    public static void main(String[] arg) {
    ServerAgent s = new ServerAgent();
    ServerThread1 st1 = new ServerThread1("Thread1",s);
    ServerThread2 st2 = new ServerThread2("Thread2",s);
    st1.start();
    st2.start();

    If I close the Runtime.exec..........Everything works
    well......)You don't empty the output of the command, that blocks the process.
    A citation from
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    Why Runtime.exec() hangs
    The JDK's Javadoc documentation provides the answer to this question:
    Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
    Try out something like this:
    String s;
    try {
       Process myProcess =
       Runtime.getRuntime().exec("ls -l"));
       DataInputStream in = new DataInputStream(
              new BufferedInputStream(myProcess.getInputStream()));
        while ((s = in.readLine()) != null) {
            out.println(s);
    catch (IOException e) {
        out.println("Error: " + e);
    }Another source of trouble under Unix is not having the correct permission for that user that executes the Java VM, which will be the permissions for the spawned subprocess. But this probably not the case, as you see something after exit.
    Regards,
    Marc

  • External commands in runtime exec

    Im trying to run commands from the Sleuthkit in a java GUI. These commands have no problem running from the konsole as all the paths etc. have been set up, but when I try to run them with the java runtime exec() they wont work. Similarly,i run standard linux commands in this gui aswell and they run without problem.
    Any ideas whats weong?
    Thanks.

    You didn't tell us exactly what you're doing.Its a forensic GUI that runs konsole based commands
    and displays the ouput in a JText areaThat tells us nothing useful. By "exactly what you're doing," I mean the Java code and the command it's exec()ing.
    >
    You didn't tell us what "doesn't work" means.The 'basic' linux commands work fine in the gui, its
    just the sleuthkit ones that wont run or return
    anything when executed using the runtime exec(). Even
    though running these commands in a konsole works
    fine. THis means all paths have been set.
    Any ideas on a different way to run them or should I
    include more than just the command used on the
    konsole?That still doesn't tell us what "doesn't work" means.
    My previous response still applies.

  • Runtime.exec does not work for commands with lengthy outputs

    I need to use Runtime.exec to run some custom commands on a Unix box. I have been doing this for quite some time now and had begun to feel comfortable when recently I started facing a problem. The thing is, whenever there is a command which prints a lot of data on to the console, the program is not able to exit from the waitFor method. Is there some thing that can be done about this?
    Following is a part of the code I use:
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec (command);
    System.out.println ("Got the process");
    int exitValue = p.waitFor();
    System.out.println ("Exit value: " + exitValue);When the output of the "command" is lengthy, it hangs after printing "Got the process".
    PS: By lengthy output, I mean that the command results in printing lines to the console which might be more than 100 in number. Say, something like what "ls -R /" would do in Unix / Linux.

    From java.lang.Process API doc:
    The Runtime.exec methods may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (Process.getOutputStream(), Process.getInputStream(), Process.getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
    So you need to consume the process' output. Check the StreamGobbler example from this article.
    Hope it helps.

  • How to capture Runtime.exec() output? doesn't seem to work?

    This is the first time I've used Runtime.exec();
    Here's the code:
    Runtime rt = Runtime.getRuntime();
                process = rt.exec(jobCommand);
                BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line=null;
                while((line=input.readLine()) != null) {
                     System.out.println("OUTPUT: " + line);
                int exitVal = process.waitFor();
            } catch(Exception e) {
                 e.printStackTrace();
            }//end catchas you can see, this is just copied and pasted out of the standard example for this method.
    When it gets to the line:
    while((line=input.readLine()) != null)
    it doesn't read anything. However, when i run the SAME exact command from the windows CMD prompt i get a ton of output.
    what am i doing wrong here?
    thanks.

    Welcome to the forum!
    >
    as you can see, this is just copied and pasted out of the standard example for this method.
    >
    No one can see that - you didn't post a link to the example you said you copied.
    >
    it doesn't read anything. However, when i run the SAME exact command from the windows CMD prompt i get a ton of output.
    >
    No one can see what command you are talking about; you didn't post the commnd or even describe what output you expect to get.
    >
    what am i doing wrong here?
    >
    What you are doing wrong is not providing the code you are using, the command you are using or enough information about what exactly you are doing.
    No one can try to reproduce your problem based on what you posted.

  • How to display Runtime.exec() command line output via swing

    Hi all, I'm new to java but have a pretty good understanding of it. I'm just not familiar with all the different classes. I'm having trouble capturing the output from a command I'm running from my program. I'm using Runtime.exec(cmdarray) and I'm trying to display the output/results to a JFrame. Once I get the output to display in a JFrame, I'd like it to be almost like a java command prompt where I can type into it incase the command requires user interaction.
    The command executes fine, but I just don't know how to get the results of the command when executed. The command is executed when I click a JButton, which I'd like to then open a JFrame, Popup window or something to display the command results while allowing user interaction.
    Any examples would be appreciated.
    Thank you for your help in advance and I apologize if I'm not clear.

    You can get the standard output of the program with Process.getInputStream. (It's output from the process, but input to your program.)
    This assumes of course that the program you're running is a console program that reads/writes to standard input/output.
    In fact, you really should read from standard output and standard error from the process you start, even if you're not planning to use them. Read this:
    When Runtime Exec Won't

  • Runtime.exec output lost when executing ftp.

    I'm writing application, which can execute command line scripts.
    I'm executing Runtime.exec("cmd") and then writing commands into output stream. I'm continously reading from input and error stream, so that's not the case.
    Everything goes fine while I'm executing simple commands, like: dir, cd.
    The problem begins when I try to execute more sophisticated commands, like ftp.
    Here is the scenario:
    ftp server_nameFtp asks for user name
    userAfter providing user name, the output is lost. There are no more characters in InputStream ever. The application doesn't hangs, because ftp actually performs next commands (password, cd, get file). It is just output that isn't shown.
    Is it known problem or am I doing something wrong?
    Please, help.

    I post some code:
    import java.util.*;
    import java.io.*;
    class StreamGobbler extends Thread
        InputStream is;
        String type;
        char[] buf = new char[1000];
        StreamGobbler(InputStream is, String type)
            this.is = is;
            this.type = type;
        public void run()
            try
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                boolean write = false;
                while (true) {
                     StringBuffer buffer = new StringBuffer();
                     while (br.ready()) {
                          int chars = br.read(buf, 0, 1000);
                          buffer.append(buf, 0 ,chars);
                          write = true;
                     if (write) {
                          System.out.print(type + ">" + buffer.toString());
                          System.out.flush();
                          write = false;
                    try {
                             Thread.sleep(1000);
                        } catch (InterruptedException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                } catch (IOException ioe)
                    ioe.printStackTrace(); 
    class StreamForward extends Thread
        InputStream is;
        OutputStream os;
        StreamForward(InputStream is, OutputStream os)
            this.is = is;
            this.os = os;
        public void run()
            try
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                OutputStreamWriter wr = new OutputStreamWriter(os);
                String line=null;
                while ( (line = br.readLine()) != null) {
                    wr.write(line+"\n");
                    wr.flush();
                } catch (IOException ioe)
                    ioe.printStackTrace(); 
    public class GoodWindowsExec
        public static void main(String args[])
            try
                String osName = System.getProperty("os.name" );
                String cmd = new String();
                System.out.println("OS: "+osName);
                if( osName.equals( "Windows NT" ) || osName.equals("Windows XP"))
                    cmd = "cmd.exe" ;
                else if( osName.equals( "Windows 95" ) )
                    cmd = "command.com" ;
                Runtime rt = Runtime.getRuntime();
                System.out.println("Execing " + cmd);
                Process proc = rt.exec(cmd);
                // any error message?
                StreamGobbler errorGobbler = new
                    StreamGobbler(proc.getErrorStream(), "ERROR");           
                // any output?
                StreamGobbler outputGobbler = new
                    StreamGobbler(proc.getInputStream(), "OUTPUT");
                StreamForward forward = new
                     StreamForward(System.in, proc.getOutputStream());
                // kick them off
                errorGobbler.start();
                outputGobbler.start();
                forward.start();
                // any error???
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);       
            } catch (Throwable t)
                t.printStackTrace();
    }This is example code, which demonstrate this problem.
    It creates new cmd process and forwards to it standard input. Process output and error streams are displayed on standard output.
    Basically you can execute dos commands by entering them from keyboard.
    Try:
    dir
    cd something
    etc.
    Now, to show a problem try:
    ftp your_favorite_server
    The program should ask for username. Enter username. Nothing is displayed. Notice that ftp is still running and executing commands, but doesn't display any output.
    Any clue, why this is happening?

  • Runtime.exec() output streams

    Hi,
    I am using Runtime.exec() to execute a whole slew of commands - running batch files and executables. It is really important that I can see the output of my programs, and the fact that Runtime.exec() doesn't spawn its own Command-Prompts is a little disconcerting. In order to get around this, I am handling the stdout and stderr output streams from the processes synchronously with threads (as detailed in the Java Pitfall article - http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html). I call Runtime.exec(command[], env[], dir) where command contains "cmd.exe" "\C" command.
    My question is, if one of my processes crashes, will my threads receive ALL of the output from stdout and stderr just as a Command-Prompt would? If not, what is the workaround? Using Psexec to run the processes seems to bring up the Command-Prompts like I would like it to, but that doesn't always behave the way it should be, so I cannot rely on that just to see the command prompts.
    I don't want to have to switch to C# or C++ to do this at this point, but if there's no real answer, it looks like I might have to.

    cotton.m wrote:
    munky135 wrote:
    Hi,
    I am using Runtime.exec() to execute a whole slew of commands - running batch files and executables. It is really important that I can see the output of my programs, and the fact that Runtime.exec() doesn't spawn its own Command-Prompts is a little disconcerting.Hilarious. Oh. You were being serious there were you? :|Yes, I was being serious. I call runtime exec and I am not getting Command-Prompts to pop up, their output is being piped to my Java application. Reading directly from the API:
    The Runtime.exec methods may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (Process.getOutputStream(), Process.getInputStream(), Process.getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
    >
    I don't want to have to switch to C# or C++ to do this at this point, but if there's no real answer, it looks like I might have to.Based on your attitude you should switch. You obviously hate Java and are ready to see faults that don't exist based on misconceptions that you hold. Fine, to each their own. Choose a language you like then. Which at a guess I would say is likely VB.Huh? I love Java. Any misconceptions I hold are from this guys article here - http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • How to capture output of java files using Runtime.exec

    Hi guys,
    I'm trying to capture output of java files using Runtime.exec but I don't know how. I keep receiving error message "java.lang.NoClassDefFoundError:" but I don't know how to :(
    import java.io.*;
    public class CmdExec {
      public CmdExec() {
      public static void main(String argv[]){
         try {
         String line;
         Runtime rt = Runtime.getRuntime();
         String[] cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E.java";
         Process proc = rt.exec(cmd);
         cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E";
         proc = rt.exec(cmd);
         //BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
         BufferedReader input = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
         while ((line = input.readLine()) != null) {
            System.out.println(line);
         input.close();
        catch (Exception err) {
         err.printStackTrace();
    public class E {
        public static void main(String[] args) {
            System.out.println("hello world!!!!");
    }Please help :)

    Javapedia: Classpath
    How Classes are Found
    Setting the class path (Windows)
    Setting the class path (Solaris/Linux)
    Understanding the Java ClassLoader
    java -cp .;<any other directories or jars> YourClassNameYou get a NoClassDefFoundError message because the JVM (Java Virtual Machine) can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.
    javac -classpath .;<any additional jar files or directories> YourClassName.javaYou get a "cannot resolve symbol" message because the compiler can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.

Maybe you are looking for

  • Create a new Database in an other server using a copie of RMAN backup

    Hi all, I want to create an other instance for our production database. We have disk and tape in rman backup. My question is can i create a new database using our disk backup in an other server? If some procedure or steps is there, email it to my adr

  • Playing wav files at different pitch

    Hi! I get the impression that the java sound package is overcomplicated. What I want to do is to generate music by playing sound files at different pitch (nothing special, I think). This means, program start -> load some files. mouse click -> play a

  • Download of 10.7.4. upgrade fails

    I boughht a used MacBook Air and installed my system via TimeMachine. But it's an older backup with only 10.7.3. I tried the systems Software Update, but it fails after loading over 90% of the data. Then I tried manual downloading the files for combo

  • Track pad not scrolling after 10.9.5 update

    My trackpad is not scrolling correctly in specific programs.  It gets held up, i need to scroll up and down to get it started.  It is not working in my online school program but works fine on other safari pages, like this one.  Any suggestions to fix

  • TfsBuild associated with dacpac database publication with replication

    In the past deployment/publication via Dacpac took about 14 minutes in our development environment.  Now, that is after we set up transaction replication it is taking two or more hours.  It seems the dacpac is identifying deltas where there are none.