3

i am trying to run commands using java program,but p.waitfor() function waits forever.What is wrong with the code?

import java.io.*;

public class doscmd
{
  public static void main(String args[]) throws InterruptedException
  {
    try
    {
      Process p=Runtime.getRuntime().exec("cmd /c dir");
      p.waitFor();
      BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
      String line=reader.readLine();
      while(line!=null)
      {
        System.out.println(line);
        line=reader.readLine();
      }
    } 
    catch(IOException e1) {}


    System.out.println("Done");
  }
}
Robᵩ
  • 154,489
  • 17
  • 222
  • 296
Salih Erikci
  • 4,976
  • 11
  • 36
  • 68

3 Answers3

5

Is the directory large? Maybe p fills up its output buffer and stalls waiting for a reader to consume something so it can finish writing out the directory listing.

You should probably move

p.waitFor();

to the end of the method.

Mike Samuel
  • 114,030
  • 30
  • 209
  • 240
1

You have to access your InputStream and ErrorStream before you're calling waitFor(). You should take a look at that question too for more details on how it works.

Community
  • 1
  • 1
talnicolas
  • 13,437
  • 7
  • 35
  • 55
1

Your directory structure is too large. Move your p.waitfor() to

Process p=Runtime.getRuntime().exec("cmd /c dir");
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
System.out.println(line);
line=reader.readLine();
}
p.waitFor();

I tried running running this in C:\programfiles works fine.

RanRag
  • 46,455
  • 34
  • 109
  • 162