How do I execute a Windows command

I want to be able to execute, for example, a 'dir' command and capture the output for parsing.

Thanks for the reply. Here is the program I tried:
import java.io.*;
public class TestProcess
     public static void main(String[] args)
          throws Exception
          // execute the command
          Process process = Runtime.getRuntime().exec( args );
          // read the output from the command
          String line;
          BufferedReader output = new BufferedReader( new InputStreamReader( process.getInputStream() ) );
          while ( (line = output.readLine()) != null )
               if (line.trim().length() > 0)
                    System.out.println( line );
          output.close();
This is how I tested it:
java TestProcess notepad (works ok)
java TestProcess java (works ok, I get java help displayed)
java TestProcess command /c dir
I get>>> Exception in thread "main" java.io.IOException: CreateProcess: command /c dir error=0
java TestProcess command.com /c dir
it hangs
I'm running on Windows 98. Any suggestions?

Similar Messages

  • How can I execute a dos command?

    I tryed so:
    import java.io.BufferedReader;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintStream;
    public class Builder {
         public static void main(String[]args)
                   //makeFile();
                   execute();
         * @author Savio
         * @description Esegue comando dos
         * @throws IOException
         public static void execute()
              try
                   Runtime will = Runtime.getRuntime();
                   Process pid=will.exec("cmd /c c:prova.bat");
                   InputStreamReader isr = // step 3
                        new InputStreamReader( pid.getInputStream() );
                        BufferedReader br = new BufferedReader( // step 4.
                        isr );
                        String line;
                        while ((line = br.readLine()) != null)
                        System.out.println(line);
              catch (IOException e)
                             e.printStackTrace();
         * @author Savio
         * @description Crea e scrive un file
         * @throws IOException
         public static void makeFile() throws IOException
              FileOutputStream file=new FileOutputStream("c:/condor/bin/file.submit");
              PrintStream out=new PrintStream(file);
              out.println("### SUBMIT DESCRIPTION FILE ###");
              out.println("Universe = java");
              out.println("Executable = job.class");
              out.println("Jar_files = job.jar");
              //out.println("Arguments = "+args[0]+" "+args[1]+" "+args[2]+" "+args[3]);
              for (int i=0; i<10;i++)
                   out.println("Output"+i+"txt");
                   out.println("Error"+i+".txt");
                   out.println("Log"+i+".log");
    This doesn't works!!
    But, if I execute my .bat from dos it works... what's the problem?
    Can you help me!!!
    I'm angry! :)

    Please use code tags when posting code.
    Use ProcessBuilder or Runtime.exec(String, String[])

  • How to execute a scenario from Windows command prompt

    Hi,
    I have a package which is executing fine from Designer. But the same scenario if I am trying to execute from windows command prompt, then it is giving error.
    The package is getting a refresh variable, passing to interface which is creating a file from table, this file is then getting FTP'ed to another server.
    I am executing following command -
    startscen OB_TAB_TO_FILE_PKG 001 ODICTX "-v=2"
    The error is -
    A JDK is required to execute Web Services with OracleDI. You are currently using
    a JRE.
    OracleDI: Starting scenario OB_TAB_TO_FILE_PKG 001 in context ODICTX ...
    java.sql.SQLException: socket creation error
    at org.hsqldb.jdbc.jdbcUtil.sqlException(jdbcUtil.java:67)
    at org.hsqldb.jdbc.jdbcConnection.<init>(jdbcConnection.java:2451)
    at org.hsqldb.jdbcDriver.getConnection(jdbcDriver.java:188)
    at org.hsqldb.jdbcDriver.connect(jdbcDriver.java:166)
    at com.sunopsis.sql.SnpsConnection.u(SnpsConnection.java)
    at com.sunopsis.sql.SnpsConnection.c(SnpsConnection.java)
    at com.sunopsis.sql.i.run(i.java)
    DwgJv.main: Exit. Return code:-1
    Please let me know where I am going anything wrong.
    Thanks,
    Himanshu

    Hi,
    you need to make the necessary changes to the %odi%\bin\odiparams.bat config file, under the "Repository Connection Information" section so that startscen knows how to extract metadata from your repository.
    You apparently have left the default settings to the Hypersonic demo repository. Is that the technology your repository is hosted on?

  • How to execute a shell command?

    What class and method should I use to set an environment variable on a local system? And how do I execute a shell command in Java?
    Thanks!

    I don't know about setting environment variables from java, but I do know how to execute system commands (and from there you could modify environment variables).
    Use Runtime.getRuntime().exec()
    There are quite a few pitfalls with using this though...
    1. It's platform dependent
    2. Doing this creates a Process. If this process has output, you need to read this, otherwise the output buffer will overflow, and that would be bad... Input is not so bad (either supplying it or not ;)
    3. If you use Win for example, and want to do a "dir", there are complications, as there is no dir.exe file, and hence it can't be executed... Do a search for this topic, there's plenty on how to get around it.
    Anyway, there's plenty more info on Runtime.getRuntime().exec(), have a look around.
    Cheers,
    Radish21

  • Executing a SQL Command in my bean class

    Hello everyone,
    I'm using JDeveloper 12.1.2.0.0.
    I have an interest in executing a query in my bean method. I've done some research and i still got a code but it can't find the method that the method requires so i tried to added the query in my AppModule and i've added my method as a data control but how can i access it and modify it in my bean method?
    The page with the code that doesn't find the method: http://jjzheng.blogspot.pt/2010/11/run-single-query-in-application-module.html
    Which gives me: "Method 'getDBTransaction' not found"
    The page that creates my method as a data control: http://amit-adf-work.blogspot.pt/2013/09/how-to-execute-sql-using-adf-application.html
    Is any of this the right way? How can i execute a SQL Command in my bean class?
    Regards,
    Frederico.

    This is the code I use
    // GET A METHOD FROM PAGEDEF AND EXECUTE IT
    // get the binding containe
    BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
    // get an Action or MethodAction
    OperationBinding method = bindings.getOperationBinding("YourMethodAction");
    // if there are parameters to set...
    Map paramsMap = method.getParamsMap();
    paramsMap.put("param","value")  ;    
    // execute the method
    method.execute();
    List errors = method.getErrors();
    if (!errors.isEmpty())
       // handle errors here errors is a list of exceptions!
    // no error resume normal work
    Timo

  • Messages window (Command-0) not showing up?

    Does anyone know how to get the Messages window (Command-0) to show up automatically when it's closed and a new message comes in? 
    I've been missing a ton of messages since installing ML because I don't check the notification list every 2 minutes, and the Messages screen doesn't pop up automatically after I close it and a new message comes in.

    Yup, this just happened to me too, and I came here looking for a solution.
    The old way worked so well: new message? new window appears. Now I eventually noticed from the dock badge that someone has been talking to me, but otherwise I wouldn't have known.
    I'd also love to automatically have separate windows for each conversation, instead of manually clicking Open Chat In Separate Window each time, but maybe that's a subject for another thread!

  • Execute an Unix command with pipe

    Hi,
    How do I execute a unix command with pipe from JAVA runTime.exec(cmd)? for example: "ls -l |wc -l"
    should return number of files. However, there is no output result. If I use "ls -l" as command argument, it gives file list.
    Here is my program:
    public static void main(String[] args) {
    try {
    Runtime runCmd = Runtime.getRuntime();
    System.out.println("sys testing");
    Process retProc = runCmd.exec(args[0]);
    BufferedReader bread = new BufferedReader
    (new InputStreamReader(retProc.getInputStream()) );
    String out = bread.readLine();
    while ( out != null ) {
    System.out.println(out);
    out = bread.readLine();
    DataOutputStream outSt = new DataOutputStream(retProc.getOutputStream() );
    outSt.writeChars(args[1]);
    outSt.flush();
    } catch (Exception ie) {
    ie.printStackTrace();
    Thanks in advance,
    Jeff

    I got my answer !
    No need to reply

  • Execute (API) UI Command

    Hi,
    Is there a way to integrate a UI Command in a Java iView?
    How can I execute an UI Command and show the Component in the jsp-File?
    Regards,
    Gerhard

    Did you search this forum before posting this question?
    It is very rude to post a question to a forum that has been answered so many times and that is easily findable in the forum...
    Process p = Runtime.getRuntime().exec("your command");
    BufferedReader read = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while( (line = read.readLine()) != null)
      System.out.println("OUT>>>" + line);
    //

  • Executing a shell command

    Hi,
    I'm new hier and have a short question. How do I execute a shell command from Java code?
    Have a nice day and lot of fun
    Yury

    Search the forum. This is explained well in other threads

  • Executing a DOS Command from JSP

    How do i execute a Dos command from within JSP. I would like to execute a sql Loader command .
    Thanks

    You use Runtime.execute().
    Take a look here for a few of the tricks involved in it:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • 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/]
    ~

  • How to Execute Power Shell Command From Windows Application.

    Hi All Experts,
    I want to execute power shell commands from my windows application.
    Is it possible ?
    Please let me know your comments..
    Thanks.

    I have not tried this, but apprently it is easy as in the sample pasted below. please see this article for more details
    http://geekswithblogs.net/Norgean/archive/2012/09/19/running-powershell-from-within-sharepoint.aspx.
    Let me know how it goes...
    public string RunPowershell(string powershellText, SPWeb web, string param1, string param2) {
    // Powershell ~= RunspaceFactory - i.e. Create a powershell context
    var runspace = RunspaceFactory.CreateRunspace();
    var resultString = new StringBuilder();
    try
    // load the SharePoint snapin - Note: you cannot do this in the script itself (i.e. add-pssnapin etc does not work)
    PSSnapInException snapInError;
    runspace.RunspaceConfiguration.AddPSSnapIn("Microsoft.SharePoint.PowerShell", out snapInError);
    runspace.Open();
    // set a web variable.
    runspace.SessionStateProxy.SetVariable("webContext", web);
    // and some user defined parameters
    runspace.SessionStateProxy.SetVariable("param1", param1);
    runspace.SessionStateProxy.SetVariable("param2", param2);
    var pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(powershellText);
    // add a "return" variable
    pipeline.Commands.Add("Out-String");
    // execute!
    var results = pipeline.Invoke();
    // convert the script result into a single string
    foreach (PSObject obj in results)
    resultString.AppendLine(obj.ToString());
    finally
    // close the runspace
    runspace.Close();
    // consider logging the result. Or something.
    return resultString.ToString();
    Ok. We've written some code. Let us test it.
    var runner = new PowershellRunner();
    runner.RunPowershellScript(@"
    $web = Get-SPWeb 'http://server/web' # or $webContext
    $web.Title = $param1
    $web.Update()
    $web.Dispose()
    ", null, "New title", "not used");
    -Sangeetha

  • How to get rid of the command window....

    How to get rid of the command window, automatically, once the .bat file which execute the .jar has been executed?
    Znx

    If you don't want the command window to show, use:
    javaw yourClass
    instead of...
    java yourClass

  • How to Invoke tasks created in FrameMaker Publishing Server from the Windows command line

    Hi All ,
    i would like to know how can we Invoke tasks and schedules created in FrameMaker Publishing Server from the Windows command line.
    we used publishing server mainly to convert Frame maker files into PDF and that should be do progarmatically without manual intervention on Demand.
    so could you please let us know how can i invoke rthe task creted to convert FM file to PDF in FrameMaker Publishing Server from the Windows command line.
    please let me know the command to execute .
    thank you and waiting for valuable response.
    best regards
    Ramesh babu

    Please see http://blogs.adobe.com/techcomm/2011/03/adobe-framemaker-server-10-and-its-command-line-ca pability.html for the same.
    Harish Dhawan

  • How to execute Linux OS command  from ODI

    We have installed Oracle data integrator on windows machine and want to execute linux OS command in a procedure or scenario from ODI .
    How could i do that ?
    I can see os command elements but they do not work, only windows commands work.There should be linux technology i think

    Obviously you can execute Unix OS commands only on Unix OS. Why do you expect Windows to understand it?
    The solution in your case would be executing your ODI scenarios with an Agent installed on Unix machine.
    Cheers

Maybe you are looking for

  • Firefox 9.01 just crashes on Windows 7 x64

    Firefox just stops working on my computer. I checked the crash reports and it does not show the crash.

  • ABAP Dump Problem - SYNTAX_ERROR

    Error in ABAP application program. The current ABAP program "SAPMSSY1" had to be terminated because one of the statements could not be executed. Hello Gurus In our quality system, we are facing problem in this ABAP Dump it generates more than 10000 t

  • Help needed - Missing Files in Aperture

    Hi All: A quick question: I initially imported RAW files in to a new project. During some time I was doing adjustment to these files, a subset of these files disappeared from the browser (I checked under "all image library" and the project). I can't

  • Tables for condition record

    Hi Guru, I was viewing Purchasing condition record in MEK3.On initial screen drop down menu it is showing some condition type.I am not clear from where these condition types are picked up. Can any one explain basis on which condition record are picke

  • IMac shuts down after gray screen

    I accidently unplugged my iMac while it was on. Now it turns on shows the gray screen with Apple logo then an empty progress bar flashes below the logo a couple of times and then it shuts off. I've tried resetting my PRAM, unplugging everything from