Displaying a shell from within a Java program

Hi,
For some long and twisted reason, I need to execute native programs from a Java program. Since this program is only every intended to be run on Linux, this doesn't bother me breaking the x-platform rules for Java! So, Runtime.exec() is the normal way to do this.
However, Runtime.exec() runs executes the command and then dishes basck the output once it's finished. The external program I wish to run takes a while and actually prints various pieces of feedback during its processing. I'd like to display this feedback to the user as it happens, rather than dumping it all at the end.
I can't think of anyway to do this. I've been looking for "Java shells" but they are reimplemented shells with only let you run classes on the classpath. Any ideas from the gurus around here?
Cheers

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 GoodLinuxExec
public static void main(String args[])
if (args.length < 1)
System.out.println("USAGE: java GoodLinuxExec <cmd>");
System.exit(1);
try
Runtime rt = Runtime.getRuntime();
System.out.println("Execing " + args[0]);
Process proc = rt.exec(args);
// 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();
stolen from this article and adapted to suit an os which does not start with the letter W.

Similar Messages

  • Start a WS application from within a java program

    Hi,
    I need to start a WebStart application from within a java program. Therefore I develeoped a class which starts javaws.exe within its main-method like this:
    try {
    Runtime.getRuntime().exec(
    "c:\\java web start\\javaws.exe http://a.b/c.jnlp"
    } catch (Exception e) {
    e.printStackTrace();
    And that did not work. Java Web Start tries to start the .jnlp program but returns with the message, that the app-desc|applet-desc|installer-desc|component-desc is missing. But it is there: It is an applet and thus I defined an applet-dec.
    I tried to do it from a command line with the followinf command:
    java -Djnlpx.home="C:\abc" -cp "C:\abc\javaws.jar" com.sun.javaws.Main http://a.b/c.jnlp
    And that works. But using this command from within my jjava prog using the Runtime.exec() method does not work.
    By the way, simply type "javaws http://a.b/c.jnlp" at the command line does not work.
    Can anybody help me? How may I start a .jnlp program within another java program.
    Kind Regards,
    Tobias Neubert

    Hi,
    I recently had a quite similar problem. At least the error message by the Java Web Start application on Mac OS X complained about the same error (app-desc|applet-desc|installer-desc|component-desc). It turned out to be some bad invisible characters in the jnlp file. I copied some sample from a web page which for some reason contained some unicode chars that the parser doesn't like. Use a different text editor or the less command on unix to see if there are some strange characters in you jnlp file.
    But it seems strange that it does work from the command line and not from your code.
    -Stefan

  • Executing a Java Program from within a Java Program

    I need to execute the following Java Program from withing another Java Program. The office toolbar command line is
    D:\WINDOWS\system32\java.exe -cp E:\Development\Eclipse\UpdateServer\Classes -server -showversion UpdateServer
    I can find no combination of ProcessBuilder commands, including those that include "Cmd.exe /c" that will make this program run from within another Java Program. All the examples I can find only show how to run Windows *.exe programs. I keep getting error 123 from ProcessBuilder.start(), but I can find no documentation for error 123.

    Assuming your code didn't get mangled by the forum
    (it's missing one "), it may be that your "-cp
    E:\\Develop.." argument is getting quoted as it has a
    space in it; try passing "-cp" and "E:\\Develop..."
    as two arguments.That worked; specifically the following tested OK:
    ProcessBuilder pb = new ProcessBuilder("D:\\WINDOWS\\System32\\Java.exe", "-cp", "E:\\Development\\Eclipse\\UpdateServer\\Classes\\", "-server", "-showversion", "UpdateServer" );
    pb.directory(new File("E:\\Development\\Eclipse\\UpdateServer\\Classes\\"));
    try{
         Process p = pb.start();
         InputStream is = p.getErrorStream();
         InputStreamReader isr = new InputStreamReader(is);
         BufferedReader br = new BufferedReader(isr);
         String line;
         while ((line = br.readLine()) != null)
              System.out.println(line);
         p.waitFor();
    }catch(IOException ioe){
    I was sure I tried that exact same code before, and it did not work, but now it does, at least at the top level (when it is in main of a test program). I will have to wait to try it until later when it is buried deep in a subroutine.

  • How to call up an executable file (eg. MSPaint) from within my java program

    How to call up an executable file (eg. MSPaint) from within my java program

    Ummm... why would you want to get MSPaint anyway? Even in the absense of real software, Java's own graphics tools are way more sophisticated - with a little time and effort, you could write a simple paint package that beat MSPaint hands down.

  • How to start a browser from within a java program?

    I want to make a help file for my java program and want to run the browser from the menu of my program.
    How can I start my browser from my program?
    A small code will be helpful.
    Thanks.
    Niteen

    This should work on Windows without having to know where the browser is located. See http://www.javaworld.com/javaworld/javatips/jw-javatip66.html for more details
      public static void viewHtml(URL url, boolean fixHtmlExtension){
          String cmd = "rundll32 url.dll,FileProtocolHandler " + url.toExternalForm();
          if (fixHtmlExtension){
            //There is a bug in rundll32. For http requests, it doesn't like .html or .htm extensions,
            //but replacing the 'm' with '%6D' works. 
            //This fix is not needed for file requests.
            if (cmd.endsWith(".htm")){
              cmd = cmd.substring(0,cmd.length()-1) + "%6D";
            else if (cmd.endsWith(".html")){
              cmd = cmd.substring(0,cmd.length()-2) + "%6Dl";
          Process process = Runtime.getRuntime().exec(cmd);
          try{
            process.waitFor();
          catch(InterruptedException e){

  • Running executable jar from within a java program

    Is there a way to launch an executable jar in a java program? I tried wrapping the jar in an exe and calling it using Runtime exec() and though this approach works it does only for windows. I want it to work for unix/linux too.

    jaki wrote:
    Yes, but it's a sub process.Nope.
    Hence the calling process doesn't quit unless the called one returns.Wrong.
    My calling program is actually a jar and what Im trying to do is delete the jar after it's done running. But the above method (of launching a separate jar doing the deletion) doesn't seem to work for the above mentioned reason.Wrong.
    If you could tell me any other way it would really be a big help.You don't need any other way. Maybe you need to allow some time for the calling program to wind up. 20 seconds may be overkill, but I'm not in the mood to find how short it can be and still succeed.
    The two classes are packaged in separate jars.import java.io.IOException;
    public class Deletee {
        public static void main(String[] args) {
          try {
             String[] cmds = {"java", "-jar", "E:/temp/Deleter.jar"};
             Runtime.getRuntime().exec(cmds);
             System.exit(0);
          } catch (IOException ex) {
             ex.printStackTrace();
    import java.io.File;
    import javax.swing.JOptionPane;
    public class Deleter {
       public static void main(String[] args) {
          File file = new File("E:/temp/Deletee.jar");
          try {
             Thread.sleep(20000);
          } catch (InterruptedException ex) {
             ex.printStackTrace();
          if (file.delete()) {
             JOptionPane.showMessageDialog(null, "Deleted");
          } else {
             JOptionPane.showMessageDialog(null, "Oops");
    }Try it and see for yourself.
    db

  • How to use .dbf files zipped into a .zip file from within a java program

    i have a .zip file containing several .dbf files.
    the zip file is automatically downloaded regularly and data from the .dbf files is inserted into the database.
    how do i facilitate automatic extraction of a zip file or how do i fetch data from the .dbf file? (this cannot be done manually)
    anu.

    you could write a little polling class checking the zip file. you can use the java.util.jar package to extract the zip file (http://java.sun.com/docs/books/tutorial/jar/api/index.html). you could also use Jakarta ant (http://ant.apache.org/manual/index.html) to do this job (core task "zip") and call ant's target file on a regular basis (dependend on the OS you use, you can set os tasks/schedules).

  • Launching applications from within a Java program,

    Hi all,
    I wish to launch an application from a menubutton. I exactly wish to launch adobe acrobat reader and a specific file. Do I need to run a system command to do this, or more specifically, how is this done in Java?
    Thanks,
    JavaRob

    what if you have the entire exe as a byte array in
    memory, write that to a file on the system, and then
    run that file.
    would that work?Yes but you would still have to use the Runtime class to excecute the file after you write it out, so it would just be easier to use the already made exe file.

  • How to execute a Perl program from within a Java prog

    How do I execute a Perl program from within a Java program.
    Lets say the Perl program that I want to execute is 'abc'. Now, 'abc' requires some input that I want to give it from within the Java program. How do I do it?
    And finally, how do I execute that Perl program from within the Java program.
    If I execute the Perl program alone then I do it in the following way -
    perl abc inp1 inp2 inp3
    where inp1, inp2, inp3 are inputs to the Perl program. I will not be able to change or modify the coding of the Perl program - 'abc' as I do not have access to its code. Its a kind of an application whose usual method of execution is in the above shown way. So, how do I execute 'abc' from within a Java program.

    what part of don't crosspost, don't you understand?
    http://forum.java.sun.com/thread.jsp?forum=4&thread=427193

  • Executing a Perl program from within a Java prog

    How do I execute a Perl program from within a Java program.
    Lets say that the Perl program that I want to execute is 'abc'.'abc' requires some input that I want to give from within the java program. How do I do that? Then I want to execute the Perl program from within the Java prog. How do I do it?

    don't crosspost.
    http://forum.java.sun.com/thread.jsp?forum=31&thread=427211&tstart=0&trange=100

  • Problem with creation of a jar file from inside a java program

    Hi,
    I am trying to create a jar file at runtime from within a java program.
    I am able to create a jar file just fine using:
    String[] jarArgs = new String[3];
    jarArgs[0] = "cvf";
    jarArgs[1] = "C:\temp\myjar.jar";
    jarArgs[2] = "C:\temp\this";
    sun.tools.jar.Main main1 = new sun.tools.jar.Main(System.out, System.err, "jar");
    main1.run(jarArgs);However, when I look at the jar it puts the absolute path to the files inside such as:
    C:\temp\this\is\my\package\Class.class
    instead of only this\is\my\package\Class.class
    When running the jar command from the command line it works just fine and I have the relative paths in my jar file.
    Does anyone have any experience with this and could help me out?
    Thanks in advance
    Edited by: mruf on Apr 11, 2008 1:51 AM

    Shouldn't jarArgs[2] = "-C C:\temp\this"

  • How to run java programs from a master java program?

    Hello,
    I have several java programs which run from the command prompt. I am seeking help with code for starting java programs from within a java program. For example, a program called master.java works something like this:
    import java.*;
    create connection pool
    create variables and result sets
    start/run slave1.java (var1, var2);
    start/run slave2.java (var3, var4, var5);
    start/run slave3.java (var1, var4);
    end of program master.java
    Each of the slave.java programs will run for up to an hour. I do not want the master.java program to pause for each slave program to stop. Instead, the master program will keep running and multiple slave programs will be running simultaneously with the master program. When a slave program starts, it is on its own. Also, if possible, I would like to have each of these slave.java programs open in a new separate command window, so I can observe each slave program running in separate windows.
    Any suggestions for code or helpful documentation are greatly appreciated.
    Thank you,
    Logan

    Thank you all.
    At the bottom of master.java I have successfully started a batch file with these lines:
    String jcmd = "cmd.exe /c start c:/data/simulations/MsgViewCount2.bat";
    Process proc = Runtime.getRuntime().exec(jcmd);
    But I still cannot get a java program to start. Here is one variation I have tried:
    String [] cmdArray = new String[2];
    cmdArray[0] = "java";
    cmdArray[1] = "slave1";
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec(cmdArray);
    This compiles, and no errors occur, but nothing happens.
    Regarding this comment:
    Why Runtime.exec? Either make the slaves Runnable or
    just call their main() methods.
    Oh, I see. Sepearate output. :PNone of the slave.java programs have any output.
    Thanks again.

  • Executing C program from with a java program

    How do you call a c program from within a java program, and parse arguments into that program and return something.
    Cheers for any reply...

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

  • Running a "heavy" program from within a java class

    Dear Java programmers,
    I 'm trying to run a software called surflex from within a java class, using the following java command:
    Runtime.getRuntime().exec( new String[ { "/bin/bash", "docking_script_2.bash"} );
    For convenience I've created the following simple bash script but for some strange reason surflex is not executed:
    #!/bin/bash
    surflex-dock-v211-linux.exe proto drug.mol2 receptor_hydro.mol2 p1;
    surflex-dock-v211-linux.exe dock drug.mol2 p1-protomol.mol2 receptor_hydro.mol2 >& 1OHR_A_output.txt;
    Can anybody help me on that (ignore the arguments, they are correctly set)? I'll try to find another, more generic example, but so far I've noticed that the same thing happens with unix grep command.
    thanks,
    Tom

    I think if you want to invoke a bash shell and give it a command to execute, you need to do
    /bin/bash -c commandrather than
    /bin/bash commandAccordingly, your call to exec should look like
    exec( new String[ { "/bin/bash", "-c" "docking_script_2.bash"} );Beyond, that, I'd suggest the following as general debugging tips and best practices:
    * As the first line of the bash script, include a line that does something simple, like touch a file, so you can see if the script is executing at all.
    * In Java, call Process.waitFor(). Its return value is the process' exit value.
    * Make sure you're gobbling stdout and stderr from the process, and giving stdin any input it needs. You'll have to do this for the process to run correctly, and you can also use what you read from stdout and stderr to debug the execution of the process. [http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]
    * You may wan to look into ProcessBuilder, rather than Runtime.exec. I haven't used it myself yet, but apparently it's supposed to be the preferred way to execute external processes.

  • Procedure to call shell script which invoke java program

    Hi
    I have requirement for a pl/sql procedure to invokes a shell script which calls java programs.
    I was using DBMS_SCHEDULTER to invoke the shell , the shell is getting invoked but it is not executing the java programs.
    appreciate your suggestions and advices .
    param1=$1
    param2=$2
    #echo "First parameter is:"$1
    #echo "Param1 is:"$param1
    if [ $# -eq 1 ]; then
    java -jar -Xmx512m abc.jar ${CONFIG_DIR} $param1
    elif [ $# -eq 2 ]; then
    java -jar -Xmx512m abc.jar ${CONFIG_DIR} $param1 $param2
    fi
    Regards

    user458361 wrote:
    Hi
    I have requirement for a pl/sql procedure to invokes a shell script which calls java programs.
    I was using DBMS_SCHEDULTER to invoke the shell , the shell is getting invoked but it is not executing the java programs.
    appreciate your suggestions and advices .
    param1=$1
    param2=$2
    #echo "First parameter is:"$1
    #echo "Param1 is:"$param1
    if [ $# -eq 1 ]; then
    java -jar -Xmx512m abc.jar ${CONFIG_DIR} $param1
    elif [ $# -eq 2 ]; then
    java -jar -Xmx512m abc.jar ${CONFIG_DIR} $param1 $param2
    fi
    RegardsYou are doing the equivalent of making THREE Left turns instead of a single Right turn
    Most likely the shell environment is woefully lacking in needed details
    add new line as below
    param1=$1
    param2=$2
    /usr/bin/env | /usr/bin/sort -o /tmp/capture.log
    # make sure above Fully Qualified Pathnames are correct for your system!
    After you invoke script from PL/SQL post content of /tmp/capture.log back here

Maybe you are looking for

  • Widget Spry ImageSlide show will not upload - error message

    I'm attempting to update our webpage (tcmfellowship.org) with a video and slideshow. The video works but I receive an error message when attemping to upload Spry Image Slide Show. The error messages are below. The photos will not upload either but I

  • Need help over this Query

    Hi, I need the Result set in the given below form.  Can any one please help me with this.  I am not able to get the 2nd most recent login date in the separate column.  Concerned Columns: Login date, login date2, login difference  Login date = Most re

  • Why do I get Open instead of Run?

    When I download the Flash installation program, I get OPEN program instead of RUN.  I don't know how to open this program. What do I need to do to be able to install Flash?  Windows 7 64bit, IE 11 32 bit, and Kaspersky Pure 3.0 virus program. I pause

  • 2 questions from a noob

    Привет Я пытаюсь установить арки. Она работает, но у меня есть проблема. Есть ли способ установить LILO на раздел paticular вместо MBR? Я только знаком с GRUB (и Gentoo процедуру установки, если на то пошло). Я установил арку раньше, и я могу себе эт

  • Licensing XML Database features

    Do we need a separate license to install XML Database feature or it is included with Oracle Database Enterprise Edition 9i? Regards Akrom [email protected]