Runtime.exec category registry error

I am calling runtime.exec() to start an application on a different machine than the one running my java application. my code is:
runtime.exec("\"\\\\computername\\sharedfolder\\executable.exe\"");
it compiles fine, but i get a pop-up window with the title "InitCategoryRegistry" that says "Couldnt create category registry"
Does anyone know how to get this to work?

Try removing the \" at the front and the rear of your String argument, as well as using Runtime.getRuntime().exec(String command)
like thus:
Runtime.getRuntime().exec("\\\\computername\\sharedfolder\\executable.exe");
Hope it works

Similar Messages

  • Error in opening a file with name in chinese characters with Runtime.exec

    The issue at hand is when I try to open a file with file name containing chinese characters in a localized environment in Windows through the following java code:
    Runtime.exec("rundll32 SHELL32.DLL,ShellExec_RunDLL {File_With_FileName_containing_Chinese_character}");
    the following error is thrown by windows.
    Cannot open file "C:\??.txt".
    with the exception
    java.io.IOException: CreateProcess: [Ljava.lang.String;@f5da06 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:566)
            at java.lang.Runtime.exec(Runtime.java:428)
            at java.lang.Runtime.exec(Runtime.java:364)
            at java.lang.Runtime.exec(Runtime.java:326)
            at Launcher.main(Launcher.java:26)
    When I try to use the same command (shown below) from the Windows Run command, the file opens sucessfully
    rundll32 SHELL32.DLL,ShellExec_RunDLL {File_With_FileName_containing_Chinese_character}
    Please suggest.
    Thanks in advance

    This may be a file association problem.  To solve that:
    In Windows 7:
    1. Right-click the file,
    2. Select "Open With" 
    select [Your Program Here]
    3. Check always use this program. 
    In Windows XP:
    1. Locate the file as you have described above
    2. Right click the file
    3. Select Open with from the pop-up menu
    4. Click Choose default program…
    5. Select Excel in the Recommended Programs box
    6. Check Always use the selected program to open this kind of file
    7. Click on OK.
    1.  Make Excel not available from Office 2007 listed under Programs and Features in Control Panel.
    2. Take a registry backup using the steps given here
    3. In the registry editor window expand HKEY_CLASSES_ROOT and navigate to .xls right and delete it.
    4. Exit Registry Editor
    5. Undo Step 1 to make Excel available.
    6.  Restart the computer and verify it the issue is fixed.
    If this answer solves your problem, please check Mark as Answered. If this answer helps, please click the Vote as Helpful button. Cheers, Shane Devenshire

  • Runtime.exec error - java.lang.NullPointerException

    Hi,
    I am trying out the example code from javaWorld that shows how to use exec to execute external command. The problem is that I aways run into java.lang.NullPointerException on line that has "Process proc = rt.exec(cmd);" I have tried to run the code under Windows XP and Windows 2003; and I get the same error message. Any idea on what might be casing this?
    Thanks,
    // GoodWindowsExec.java
    import java.util.*;
    import java.io.*;
    class StreamGobbler extends Thread
    InputStream is;
    String type;
    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;
    while ( (line = br.readLine()) != null)
    System.out.println(type + ">" + line);
    } catch (IOException ioe)
    ioe.printStackTrace();
    public class GoodWindowsExec
    public static void main(String args[])
    if (args.length < 1)
    System.out.println("USAGE: java GoodWindowsExec <cmd>");
    System.exit(1);
    try
    String osName = System.getProperty("os.name" );
    String[] cmd = new String[3];
    if( osName.equals( "Windows NT" ) )
    cmd[0] = "cmd.exe" ;
    cmd[1] = "/C" ;
    cmd[2] = args[0];
    else if( osName.equals( "Windows 95" ) )
    cmd[0] = "command.com" ;
    cmd[1] = "/C" ;
    cmd[2] = args[0];
    Runtime rt = Runtime.getRuntime();
    System.out.println("Execing " + cmd[0] + " " + cmd[1]
    + " " + cmd[2]);
    Process proc = rt.exec(cmd);
    // any error message?
    StreamGobbler errorGobbler = new
    StreamGobbler(proc.getErrorStream(), "ERROR");
    // any output?
    StreamGobbler outputGobbler = new
    StreamGobbler(proc.getInputStream(), "OUTPUT");
    // kick them off
    errorGobbler.start();
    outputGobbler.start();
    // any error???
    int exitVal = proc.waitFor();
    System.out.println("ExitValue: " + exitVal);
    } catch (Throwable t)
    t.printStackTrace();
    }

    What is System.getProperty("os.name") returning when you run on Windows XP or 2003?
    You are only filling in your cmd array when os.name is either Windows NT or Windows 95. In other cases, the elements of cmd are left as null.
    The documentation for Runtime.exec() says you will get a NullPointerException when elements of the array are null:
    http://apidoc.org/view/10563?a=exec%28java.lang.String%5B%5D%29

  • Runtime exec createProcess error

    Seeveral monts ago I get this piece of code on ee
    It gets hard disk numer via cmd.exe
    that works fine on xp but on 98 dont because there is no cmd.exe :)
    My coworker make little exe fajl (hdid.exe) which return id number and it works fine too on xp but on 98 that piece of code throws io exception
    Here is the function I use for it
    (lines under comments are lines that I have used before new hdid.exe )
    public String getKey(){
    try {
    System.out.println("check gk 0 ");
    String[] args = new String[] { KlijentPutanje.getRoot()+"/hdid.exe" };
    //String[] args = new String[] { "cmd.exe",  "/c",  "dir", "|",  "find", "/i",  "Serial Number is" };
    Process pro = Runtime.getRuntime().exec(args);
    InputStream error = pro.getErrorStream();
    InputStream output = pro.getInputStream();
    collector = new StringBuffer();
    ProcessStreamReader collectingReader = new ProcessStreamReader(output);
    Thread out = new Thread(collectingReader);
    out.start();
    out.join();
    String volumeNumber = collector.toString();
    //volumeNumber = volumeNumber.substring(volumeNumber.lastIndexOf(' '));
    volumeNumber = volumeNumber.trim();
    return volumeNumber;
    catch (Exception e){
    System.out.println("greska prilikom provere registracije - code 169");
    e.printStackTrace();
    return null;
    Here is the exception that this line throws
    greska prilikom provere registracije - code 169
    java.io.IOException: CreateProcess:
    /Grom/dev/pilot/1.0-radna/Ekspert/EkspertData/hdid.exe error=0
    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 java.lang.Runtime.exec(Unknown Source)
    at com.propisi.util.Reg.getKey(Reg.java:280)
    at com.propisi.util.Reg.execute(Reg.java:73)
    at com.propisi.SearchEngine.getSearchEngine(SearchEngine.java:130)
    at com.propisi.forme.AppletPretraga.loadReg(AppletPretraga.java:574)
    at com.propisi.forme.AppletPretraga.jbInit(AppletPretraga.java:235)
    at com.propisi.forme.AppletPretraga.init(AppletPretraga.java:167)
    at sun.applet.AppletPanel.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Can you help me 2 get hard disk number on windows98 too (with this hdid.exe pr maybe some other way)
    tia cubrovic

    That does look like a problem with you coworker's native code, not like a Java problem.

  • Runtime.exec error in windows

    When i try to run an external program with Runtime.exec() in windows 2000, i get a windows pop-up with the following error msg:
    d:\winnt\system32\ntvdm.exe
    Error while setting up environment for the application.
    I have no idea how to fix this since i have no clue to what that error means.
    Thanks
    Rumy

    I've personally just encountered the same error. I am building a piece of demonstration software to distribute with my graduate school applications to demonstrate my programming experience and I wish to include a set of programs I wrote some years ago in Pascal and C++. The software has been compiled for MS-DOS 6.0. I am using the following command to execute the software from within my Java program:
    Runtime.getRuntime().exec(new String[]{"command.com","/c","12cards.bat"});The batch file performs the appropriate setup operations for the program and runs the executable. When I run this code segment, I receive the following error:
    [16 bit MS-DOS Subsystem]
    C:\WINNT\system32\ntvdm.exe
    Error while setting up environment for the application. Choose 'Close' to terminate the application.
    I have another code segment in which I attempt to run the executable myself (without the help of command.com or the batch file). The code segment is as follows:
    Runtime.getRuntime().exec(new String[]{"12cards.exe"}, new String[0], workingDir);When I run this code segment, the following IOException is thrown:
    java.io.IOException: CreateProcess: 12CARDS.EXE 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:566)
         at (my code)I have already found the document on Microsoft's support website which describes a solution to this problem. Manually extracting the autoexec.nt, config.nt, and command.com files from the installation CD-ROM did not help.
    The most confusing element of this: 12CARDS.EXE runs fine if I execute it from Windows Explorer. It's only a problem if it's executed from within my Java program. I have two other DOS programs which I want to include as well; I am having the same trouble with them.
    Any advice will be much appreciated. Thanks!

  • Runtime.exec() error codes

    I am getting the following exception when I try doing...
    r.exec ( "cmd/c start/b notepad" );
    Want to diagnose but don't see the errorcode any where documented.
    thanks in advance.
    java.io.IOException: CreateProcess: start dir error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Win32Process.java:63)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:566)
    at java.lang.Runtime.exec(Runtime.java:428)
    at java.lang.Runtime.exec(Runtime.java:364)
    at java.lang.Runtime.exec(Runtime.java:326)
    at com.ugsolutions.aif.installer.Installer.main(Unknown Source)

    hi I am having the same problem. I have a .cmd file that needs an arguement to run. The .cmd file connects to a server via PSCP. The .cmd file works properly on it's own on the commandline with an appropriate arguement, but as for using it thru the java file - it doesnt even hang, it just doesnt execute. Can anyone help me please?
    Fin.
    CODE:
    import java.io.*;
    class ExecDemo
         public static void main(String[] args) throws IOException
              //if( args.length < 2 )
              //     System.out.println( "Please specify parameters" );
              //else
                   //System.out.println( args[0] );
                   //System.out.println( args[1] );
                   String command;
                   command = "/cmd -c package.cmd 331/Finbarr/*";
                   System.out.print( command );
                   Runtime rt = Runtime.getRuntime ();
                   try
                        Process rtProcess = rt.exec ( command ); //
                        // Print command output onto standard output
                        InputStream is = rtProcess.getInputStream();
                        InputStreamReader isr = new InputStreamReader(is);
                        BufferedReader br = new BufferedReader(isr);
                        String str;
                        System.out.println();
                        System.out.println("starting...");
                        int i = 0;
                        while ((str = br.readLine()) != null)
                             System.out.println(i + " " + str);
                             i ++;
                        is.close();
                        System.out.println("over...");
                        try
                             rtProcess.waitFor();
                        catch (InterruptedException ire)
                             ire.printStackTrace();
                   catch (IOException ioe)
                        ioe.printStackTrace();
    }

  • Tidal abends with error message: Jvm call Runtime.exec() returned null

    just wandering if this error "Jvm call Runtime.exec() returned null  Command[chmod 777] launch failed." is a tidal error and not a job command error returned from the OS server.
    thanks,
    warren

    I'm having the same problem...
    Have you been able to solve your problem yet?

  • Intermittent Error with Runtime.exec()

    I have a Windows Service for an Adaptive Server Anywhere database server that is built upon install of our application.
    One of the new things we're trying to do with our app
    requires us to shutdown this service using Java (1.4.2_06) code. This
    shutdown is done by using the runtime.exec("dbsvc -x
    ASA_SERVICE") command. Sometimes this works fine, but
    others it fails. I got the error output from the java
    command which is: Overlapped I/O operation is in progress.
    Error stopping service "ASA_SERVICE". When I try and
    shutdown the service via the Windows Service dialog I have
    no problems anytime. I see no errors in the ASA log
    file. Can someone tell me what might be
    causing the error sometimes when running this using the Java
    runtime.exec(...) command?
    Thanks,
    Cory Musselman

    Try running the command a couple of dozen times from the command line, not from Runtime.exec() but just from a plain old command line. That should give you a better idea of whether Runtime.exec() is part of the problem or not.

  • Runtime.exec error on Fedora Core

    Hi,
    I have some difficulty using Runtime.exec method on Fedora Core.
    If classpath contains "space", it cannot execute a commnad.
    It works well on Windows systems with quotation marks.
    Here's my code.
    Proccess p = r.exec("java -classpath .:\"pkg root"\" A");
    Java command regards root as a class. It is actually a half of directory name. How can I solve this problem?
    thank you for reading.

    This setting works for me on Linux:
    [ebank2@giskard ivan]$ java b
    here is a - have a nice day![ebank2@giskard ivan]$ cat "a b"/a.java
    public class a {
    public static void main (String a[] ) {
    System.out.println("here is a - have a nice day!");
    }[ebank2@giskard ivan]$ cat b.java
    import java.io.*;
    public class b {
    static String s[]={ "java" , "-classpath" , "a b" , "a" };
    public static void main (String a[] ) throws Exception {
    Process p =  Runtime.getRuntime().exec(s);
    InputStream is = p.     getInputStream() ;
    int c;
    while((c=is.read()) != -1) System.out.print((char)c);
    }

  • 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("Perl Script writing and reading on I/O"), handling Streams

    Hi all !!
    In a first place : sorry for my english if it's not really understandable but I try to do as good as possible !
    I'm writing a GUI with Swing that will allow (in one of my multiple tables) the user to run a Perl Script.
    This Perl Script ask the user to choose a Folder ... then read all the files in this folder and for each file (xml File), extract the datas and put them in a database. But when a file that has to be inserted in the database contains this line : <Template_Used name="ST1.mtt"> and if the Template table in my database doesn't have the "ST1.mtt" stored ... the Perl Script ask to the user to give him the path of the file "ST1.mtt" so that the script can put the "ST1.mtt template" datas in the database.
    This script runs well when it is from a windows console.
    But I need a graphic interface !!!
    So I created a JButton "Process a folder".
    When the button is pressed, a JFileChooser appears and ask the user which Folder has to be processed.
    Then a Process is created with the command : ("cmd.exe /C \"C:\\Program Files\\Fluke\\Ansur\\ProcessFolder.bat\").
    The BatFile :
    {code}cd C:\Documents and Settings\tsd\Desktop\Gael-Project\Project_Files
    perl Process.pl
    exit{code}
    At this moment everything is working well.
    But my Process.pl (which is 300 lines long ... and that you don't even want to hear about), ask in a first time the Path of the folder to process and sometimes ask the path to a file (a template file).
    So I need to read and wirte on the STDIN/STDOUT during the exec of the Process.
    In order to handle this I created two different threads : one reading the Process.getInputStream with a BufferedReader and one other writing on the Process.getOutputStream with a PrintWrinter.
    What I need to do is :
    When I read a line from the InputStream saying "I need the path of the ST1.mtt file", I should run a JFileChooser ... the user find the file in the computer ... and I write in the OutputStream the path of the file, so that my Perl Script doesn't have un Unitialised value on <STDIN> and can continue to process !!
    I'm pretty sure it's possible ... because at the moment I just used a trick :
    When the user push the "process a folder" button, I write the paths in the OutputStream before than the script needs it and it works !
    But I need to write in the OutputStream only when it is time !!!
    Any idea ??
    Here are some parts of my code :
    {code}
    String filename = File.separator+"tmp";
              JFileChooser fc = new JFileChooser(new File(filename));
              fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY );
              // Show open dialog; this method does not return until the dialog is closed
         fc.showOpenDialog(null);
         Folder = fc.getSelectedFile();
              new GoodExec(cmd);
    {code}
    {code}
    public class GoodExec {
         public static Process proc;
         public static StreamGobbler errorGobbler;
         public static StreamGobbler inputGobbler;
         public static StreamGobbler outputGobbler;
         public GoodExec(String cmd)
         try
                   Runtime rt = Runtime.getRuntime();
              proc = rt.exec(cmd);
         // any error message?
         errorGobbler = new
         StreamGobbler(proc.getErrorStream(), "ERROR");
         // any input?
         inputGobbler = new
         StreamGobbler(proc.getInputStream(), "INPUT");
         // any output?
              outputGobbler = new
              StreamGobbler(proc.getOutputStream(), "OUTPUT");
         // kick them off
         errorGobbler.start();
         inputGobbler.start();
         outputGobbler.start();
         // any error???
         int exitVal = proc.waitFor();
         System.out.println("ExitValue: " + exitVal);
         } catch (Throwable t)
         t.printStackTrace();
    {code}
    {code}
    public class StreamGobbler implements Runnable
    InputStream is;
    OutputStream os;
    String type;
    Thread thread;
    public static String chaine;
    StreamGobbler(InputStream is, String type)
    this.is = is;
    this.os=null;
    this.type = type;
    StreamGobbler(OutputStream os, String type)
    this.os = os;
    this.is=null;
    this.type = type;
    public void start () {
         thread = new Thread(this);
         thread.start ();
    public void run()
    try
    if (is == null){
         PrintWriter toProgram = new PrintWriter(os);
         File FolderToProcess = ProcessFolder.Folder;
    String Folder = FolderToProcess.getPath();
    toProgram.write(Folder);
    toProgram.close();
    else {
         if (os == null){
         InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line=null;
    String comp = "Please enter the exact path of the directory that contains the files you want to process.";
    while ( (line = br.readLine()) != null){
         if (type.equals("INPUT")){
              chaine+=line+"\n";
         if (line.equals(comp)) {
              System.out.println("give directory");RUN A JFILECHOOSER AND GIVE THE DIRECTORY TO THE OUTPUTSTREAM
    System.out.println(type + ">" + line);
    is.close ();
    catch (IOException ioe){
         ioe.printStackTrace();
    {code}
    And here is an example of a simple perl script that could be used (it s a simple one !!) :
    {code}
    #!/usr/bin/perl -w
    use strict;
    print "Please enter the exact path of the directory that contains the files you want to process.\n";
    my $dir= <STDIN>;
    chomp ($dir);
    print "titallala $dir";
    if (the template of the file is not in the database){
    print "Please give me the template so that I can put it in the database";
    $dir= <STDIN>;
    chomp ($dir);
    {code}
    Thank you for your help ... if it's possible to help me !!
    Gael

    BalusC -- The line that gives me my NullPointerException is when I call the "DisplayProduct()" method. Its a dumb question, but with NetBeans how do I find out which reference could be null? I'm not very familiar with how NetBeans works with finding out how to debug. Any help you can give me would be greatly appreciated.The IDE is com-plete-ly irrelevant. It's all about the source code.
    Do you understand anyway when and why a NullPointerException is been thrown? It is a subclass of RuntimeException and those kind of exceptions are very trival and generally indicate an design/logic/thinking fault in your code.
    SomeObject someObject = null; // The someObject reference is null.
    someObject.doSomething(); // Invoking a reference which is null would throw NPE.

  • Runtime exec freezes: exec target is a executable .jar that requires stdin

    I am having a problem with the Runtime.getRuntime().exec methodology in the following scenerio:
    -- Exec.class is a program that uses a StreamGobbler to display stdout to the screen
    -- ReadInput.class is a program that requires the user enter information via the console, using stdin
    When I try to do this, the ReadInput.class locks up and freezes, presumably because its trying to use stdin which already has been gobbled up by the Exec.class ???
    Here is my code, for example, that I run with the following command (on Windows XP) :
    start.bat
    @echo off
    echo.
    javac *.java
    echo First, test the Exec.class to see if it works
    echo.
    java Exec "dir *.java"
    echo.
    echo Then, try to run a program that wants the stdin (click a key to continue)
    echo.
    pause>nul
    java Exec "java -cp . ReadInput"
    echo.
    echo (click a key to end)
    pause>nul
    Exec.java
    import java.util.*;
    import java.io.*;
    class StreamGobbler extends Thread
        InputStream is;
        String type;
        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;
                while ( (line = br.readLine()) != null)
                    System.out.println(type + ">" + line);   
                } catch (IOException ioe)
                    ioe.printStackTrace(); 
    public class Exec
        public static void main(String args[])
            if (args.length < 1)
                System.out.println("USAGE: java Exec <cmd>");
                System.exit(1);
            try
                String osName = System.getProperty("os.name" );
                   System.out.println(osName);
                String[] cmd = new String[3];
                if( osName.equals( "Windows XP" ) )
                    cmd[0] = "cmd.exe" ;
                    cmd[1] = "/C" ;
                    cmd[2] = args[0];
                else if( osName.equals( "Linux" ) )
                    cmd[0] = "command.com" ;
                    cmd[1] = "/C" ;
                    cmd[2] = args[0];
                Runtime rt = Runtime.getRuntime();
                System.out.println("Execing " + cmd[0] + " " + cmd[1] + " " + cmd[2]);
                Process proc = rt.exec(cmd);
                // any error message?
                StreamGobbler errorGobbler = new
                    StreamGobbler(proc.getErrorStream(), "ERR");           
                // any output?
                StreamGobbler outputGobbler = new
                    StreamGobbler(proc.getInputStream(), "OUT");
                // kick them off
                errorGobbler.start();
                outputGobbler.start();
                // any error???
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);       
            } catch (Throwable t)
                t.printStackTrace();
    public class ReadInput {
       public static void main (String[] args) {
          //  prompt the user to enter their name
          System.out.print("Enter your name: ");
          //  open up standard input
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          String userName = null;
          //  read the username from the command-line; need to use try/catch with the
          //  readLine() method
          try {
             userName = br.readLine();
          } catch (IOException ioe) {
             System.out.println("IO error trying to read your name!");
             System.exit(1);
          System.out.println("Thanks for the name, " + userName);
    }  // end of ReadInput classEdited by: sabre150 on 21-Jul-2011 11:26
    Added [ code] tags to make the code readable.

    When you call proc.getInputStream(), you are opening an InputStream in your app to read from the process's stdout.
    If that process "needs stdin", that is, if it normally runs by a user typing stuff at a terminal after it launches, then you have to call proc.getOutputStream() to get an OutputStream that your app can use to feed the process's stdin. So if you're trying to have your app read from the terminal (your app's stdin/System.in) and push that to the process you're launching, then after reading a line from System.in, your app would need to write that line to the OutputStream that you get from proc.getOutputStream().

  • 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

  • Using Runtime exec() to open and close process like java or javac

    Hi, I m a student who is learning IT and is wondering if
    Runtime exec() can run and stop commands like java and javac?
    Can someone post the code to do so here?Thank you

    Well, Here is my complete code:
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class StreamGobbler extends Thread
    InputStream is;
    String type;
    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;
    while ( (line = br.readLine()) != null)
    System.out.println(type + ">" + line);
    } catch (IOException ioe)
    ioe.printStackTrace();
    class Program implements Runnable
         Process proc;
    String args[];
         String[] cmd = new String[4];
         boolean isGone=false;
         public Program(String args[])
              this.args=args;
         public void run()
              if (isGone==true)
                   try
                        Runtime.getRuntime().exec(cmd).destroy();
                   catch(IOException e)
                        System.out.println("Error: "+e.toString());
                   System.out.println("User abort");
         public void start(String args[])
              if (args.length < 1)
    System.out.println("USAGE: java GoodWindowsExec <cmd>");
    System.exit(1);
    try
    String osName = System.getProperty("os.name" );
    if( osName.equals( "Windows NT" ) )
    cmd[0] = "cmd.exe" ;
    cmd[1] = "/C" ;
    cmd[3] = args[0];
    else if( osName.equals( "Windows 95" ) ||osName.equals( "Windows 98" ))
    cmd[0] = "command.com" ;
    cmd[1] = "/C" ;
    cmd[2] = args[0];
                        cmd[3]=args[1];
    Runtime rt = Runtime.getRuntime();
    // System.out.println("Execing " + cmd[0] + " " + cmd[1]
    // + " " + cmd[2]+" "+args[1]);                                    
    proc = rt.exec(cmd);
    // any error message?
    StreamGobbler errorGobbler = new
    StreamGobbler(proc.getErrorStream(), "ERROR");
    // any output?
    StreamGobbler outputGobbler = new
    StreamGobbler(proc.getInputStream(), "OUTPUT");
    // kick them off
    errorGobbler.start();
    outputGobbler.start();
    // any error???
    // int exitVal = proc.waitFor();
    //System.out.println("ExitValue: " + exitVal);
    } catch (Throwable t)
    t.printStackTrace();
         public void destroy()
              isGone=true;
    class test1 implements ActionListener
         String s[]={"c:\\jdk1.3\\bin\\java.exe","ContactProcessor1"};
         GUI g=new GUI();
              Program p=new Program(s);
         public test1()
              //didnt work
              g.getStart().addActionListener(this);
              g.getStop().addActionListener(this);
              g.show();
         public void actionPerformed(ActionEvent e)
              if (e.getSource()==g.getStart())
                   p.start(s);
                   p.run();
              if (e.getSource()==g.getStop())
                   p.destroy();
                   p.run();
         public static void main(String args[])
              test1 t = new test1();
    class GUI extends JFrame
         JButton start;
         JButton stop;
         public GUI()
              super();
              getContentPane().setLayout(new FlowLayout());
              start=new JButton("start");
              stop=new JButton("stop");
              getContentPane().add(start);
              getContentPane().add(stop);
              setSize(100,100);
         public JButton getStart()
              return start;
         public JButton getStop()
              return stop;
    }

  • 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

Maybe you are looking for

  • How to connect Apple TV 2 to my Library?

    When I select "Computer" in Apple TV 2 to show my Library, the Library only shows up if iTunes is running on my iMac.  Is this normal? I couldn't find anything in the Setup Guide about this. I have Home sharing enabled and the Apple TV is connected t

  • Can I get my money back? (UK)

    Hi all, I'm hoping for advice here. I live in the UK, so I could do with knowing what my rights are here. Anyway, here is the situation: I own an Apple Cinema Display 20. It is less than a year old. I really dislike it, and I would like my money back

  • The finger print scanner doesn't work 90% of the time please help! I have tried everything.

    Dose any one else have problems with the iPhone 5s finger print scanner?? I've tried rescanning, different fingers, scanning different ways. But 95% of the time it just won't work. It is soooo frustring!! I would have saved a bunch of $ and bought a

  • Itunes doesn't see my Ipod video

    I downloaded the new Itunes 7.0.2 because I bought the new 30gb video Ipod. Its the second day I spend in trying to connect Itunes with Ipod. It is working as harddisk but Itunes says that I have to reinstall Itunes in order to make the connection. I

  • Problem with asp:Button in PTWC 2.1 - onclick not rendering on second button

    I have a user control with two asp buttons in one TD tag (they both have ptrender=true on them). In the portal only the first button fires its event. The second button does not. I did a partial view source on the two buttons and I see this (button 1