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().

Similar Messages

  • Executable jar that can extract some archive nested in it and do more

    Can anyone tell me how i can extract sfx(self -extracted) archive using executable jar if this archive is included into this jar. And how to include it.
    For example: i have jar witch prints hello world to screen but also contains sfx archive in it with pictures for example, so when i double click on this jar, it should start sfx and print hello world.

    hi Dear
    I have tried following example and it works well and good. Here i m using jdk 1.6
    package mypack;
    public class Test {
    public static void main(String args[]) {
    try {
    System.out.println("Hello World");
    Process p = Runtime.getRuntime().exec("Tcpview.exe");
    System.out.println("wait status " + p.waitFor());
    }catch (Exception e) {
    e.printStackTrace();
    i have created META-INF\MANIFEST.MF file in the same folder where mypack folder stays meance my folder hierarchy is this.
    META-INF\MANIFEST.MF
    mypack\Test.class
    Tcpview.exe
    I have created jar with following command
    jar -cvfM mypack.jar *
    and executing the mypack.jar as
    java -jar mypack.jar
    If after doing something like this then also if your problem not solved then do one thing that
    In jar creation give one more option 0 meance
    jar -cvfM0 mypack.jar *
    Try and then put your comment. I have successfully runned above e.g.

  • Executable JAR file: Could not find the main class.

    Hello,
    I have a problem with making an executable JAR file.
    I have written a JAVA program that consists of five different classes of which User.java is the main class and I have saved a text document with Main-Class: User and a blank line after that.
    If I try:
    jar cmf MainClass.txt User.jar User.class Beheerder.class Operator.class Manager.class MaakVisueelSchema.class
    it makes a executable jar file which actually works! :)
    But when the Operator class trys to open the MaakVisueelSchema class the screen stays blank.
    I can run MaakVisueelSchema with java MaakVisueelSchema.
    So I tried to make an executable JAR that consists only of MaakVisueelSchema, the same way as I did for User:
    Main-Class: MaakVisueelSchema
    jar cmf MainClass.txt MaakVisueelSchema.jar MaakVisueelSchema.class
    Then I get the error message:
    Could not find the main class. Program will exit.
    from the Java Virtual Machine Launcher.
    The big difference between MaakVisueelSchema and the other classes is that MaakVisueelSchema contains a PaintComponent method and an ComponentListener. Is it possible that one of those creates the error?
    Can anyone help me with this problem?
    Thanks in advance!
    Bye!

    Yes,
    I tried:
    jar xvf MaakVisueelSchema.jar
    and it returns:
    META-INF/
    META-INF/MANIFEST.MF
    MaakVisueelSchema.classN/G. You need to manually create a manifest file in a text editor, have it point to your main class, and enter it in your jar command as an argument.

  • How do i wrap a dll inside an executable jar

    hi,
    i have an executable jar that uses jni to reference native code in a dll.
    i can launch the executable jar only if the dll is in the same directory as the jar (or in system32).
    so, i figured if i added the dll to the jar it would work. no!
    what do i do to deploy only 1 executable jar?
    thanks

    Hi anonimuds,
    I see useless &ldquo;expert&rdquo; activities here instead of giving a real response!
    You can pack a native library with bytecode if you use WebStart technology. Let look at the example tested by me. It shows Windows MessageBox from the native method.
    Here is Java class HellowWorld:
    package test;
    public class HellowWorld {
    static {
    System.loadLibrary("HellowWorld");
    public static void main(String[] args) {
    DoHellow();
    public static native void DoHellow();
    }With javah I generated C++ header:
    /* DO NOT EDIT THIS FILE - it is machine generated */*
    *#include <jni.h>*
    */* Header for class test_HellowWorld */*
    *#ifndef _Included_test_HellowWorld*
    *#define _Included_test_HellowWorld*
    *#ifdef __cplusplus*
    *extern "C" {*
    *#endif*
    * Class: test_HellowWorld
    * Method: DoHellow
    * Signature: ()V
    JNIEXPORT void JNICALL Java_test_HellowWorld_DoHellow
    (JNIEnv *, jclass);
    #ifdef __cplusplus
    #endif
    #endifWith MS Visual Studio I made a simple library with the native method implementation:
    #include "stdafx.h"
    #include "test_HellowWorld.h"
    BOOL APIENTRY DllMain( HANDLE hModule,
    DWORD ul_reason_for_call,
    LPVOID lpReserved
    return TRUE;
    JNIEXPORT void JNICALL Java_test_HellowWorld_DoHellow(JNIEnv *, jclass)
    MessageBox(0, "Hellow World!", "Message", MB_OK);
    }I compiled Java code above to test.HellowWorld.class and JNI code to HellowWorld.dll.
    Then I packed bytecode and DLL to HellowWorld.jar with batch file:
    %java_home%\bin\jar cvmf MANIFEST.MF HellowWorld.jar test/HellowWorld.class ./HellowWorld.dll
    %java_home%\bin\keytool -genkey -v -alias vitaly -keystore OlejaKeystore -storepass MyStore -keypass Caretta
    %java_home%\bin\jarsigner -keystore OlejaKeystore -storepass MyStore -keypass Caretta HellowWorld.jar vitallyWhere content of MANIFEST.MF is
    Manifest-Version: 1.0
    Created-By: 1.4.2_12 (Sun Microsystems Inc.)
    Main-Class: test.HelloWorldBefore deploying the project to Intranet Site I prepared JNLP and HTML files.
    The content of HellowWorld.jnlp file is
    <?xml version="1.0" encoding="utf-8"?>
    <jnlp spec="1.0+" codebase="http://vitallis/HellowWorld">
    <information>
    <title>HellowWorld Example</title>
    <vendor>ABC Ltd</vendor>
    <homepage href="HellowWorld.html"/>
    <description>JNI Test</description>
    <description kind="short">JNI Test</description>
    </information>
    <security>
    <all-permissions/>
    </security>
    <resources>
    <j2se version="1.3+" href="http://java.sun.com/products/autodl/j2se"/>
    <j2se version="1.3+"/>
    <jar href="HellowWorld.jar" main="true" download="eager"/>
    </resources>
    <resources os="Windows">
    <nativelib href="HellowWorld.jar" download="eager"/>
    </resources>
    <application-desc main-class="test.HellowWorld"/>
    </jnlp>The codebase value you will change to URL of your Site. And at the last, here is HellowWorld.html text
    <html>
    <head>
    <title>Java Web Start Example</title>
    </head>
    <body>
    <P>Java Web Start Example:</P>
    <P>
    <a href="HellowWorld.jnlp">JNI Example</a>
    </body>
    </html>I have tested this project on my computer and it runs fine.

  • Storing data with executable JAR

    if I have an executable JAR that needs to read and write from a text file so that users can customize the program, can I put the text file or any kind of database inside the JAR or does it have to go outside. Also, what is the best way to store such data, in a database or in a text file?

    if I have an executable JAR that needs to read and
    write from a text file so that users can customize
    the program, can I put the text file or any kind of
    database inside the JAR or does it have to go
    outside. I think it's safe to say that you'd need to create a folder to keep your files in. i.e. the Jar won't get updated.
    Also, what is the best way to store such
    data, in a database or in a text file?Depends, a small amount of simple data should go in a flat file, .txt is fine, whatever. If you have lots of (possibly complex) data and relationships between the data, etc. then you'd likely use a database.

  • Executable Jar? - Googled for hours, tried many solns, still doesn't work!

    I am fairly new to Java, and I'm just simply trying to create an executable jar that will run when I double-click on the icon.
    I have created my very basic program that uses java swing on Netbeans. I have right-clicked on the project, selected properties, and checked the packaging section to make sure that it creates a jar file. I also selected compress jar file, which some tutorial told me to do as well. (I've also tried not checking compress jar file to see if it made a difference... it didn't).
    I then went to folder options to make an association with the jar file to javaw.exe so that when I clicked on the icon, it would know to use javaw.exe to open it. When I double click on the jar file, it now just makes the error noise and nothing happens. Before I made the assocation, it would open up ultimatezip which would show me the original source code, the class file, and the manifest.mf file.
    In any event, I'm just playing around with creating an executable jar file and any advice on how to make it so that the GUI launches when I double click on it would be extremely helpful.
    Edited by: bigbamboo on Oct 13, 2009 8:41 AM

    bigbamboo wrote:
    Thanks for your prompt response. I just tried your suggestions. 1 & 2 both worked for me. I have fiddled around some more with my file association and have looked at several sites that go through it step-by-step and I have tried them all. I went to tools, folder options, and I have changed the association to javaw.exe
    I just can't figure out what's wrong.Good. So at least you know that it is the file type association that is not working correctly.
    On my Windows PC, when I edit the open Action for .jar files, the command string is
    "C:\Program Files\Java\jre6\bin\javaw.exe" -jar "%1" %*Maybe that will help. Of course, the path to your javaw.exe may be different.

  • Command line options in executable jar

    Hello,
    On a win32 system I have an executable jar that the user dbl clicks to run.
    What I would like to do is maintain this simple dbl click to run but have command line options passed to the vm. ie I would like the dbl click to invoke
    javaw -Xms60m -Xmx120m -jar myjarfile.jar
    rather than just
    javaw -jar myjarfile.jar
    Can these options be placed in the jar files manifest? If so how? (I can't see how to do it)
    Many thanks
    Mike

    why not use special .jar tool to help you to save much
    of your time?
    Thanks for the idea but it really doesn't answer my question.
    Mike
    [Edited by: jdcforumadmin1 on Jun 24, 2002 1:39 PM]

  • Runtime exception when processing target-fieldmapping

    Hi guys,
    Mine is a scenario from ECC to MDM. I have to trigger INFORECMASS Idoc through Transaction ME18. It's working fine and I am able to see the correct output in  the appropriate folder in MDM.
    I gotta new requirement. Now it's triggering one Idoc for one record and we want an xml for about say 1000 records or may be even 1500 records. Using Transaction MDM_CLNT_EXTR we trigger an Idoc that has many segments, mainly over a range, and then I get the following error in SXMB_MONI
    Runtime exception occurred during application mapping com/sap/xi/tf/_MM_INFRECMASS_ECC_to_MDM_; com.sap.aii.mappingtool.tf7.MessageMappingException: Runtime exception when processing target-fieldmapping /ns0:MT_INFRECMASS_Receiver/INFREC_Receiv~<
    This is the error that I get. The strange thing is that even now when I trigger using ME18, I am getting the correct output. Why am I getting this error when I trigger the other way around ?
    Regards
    Harish Babu

    Hi Baskar,
    I changed the mapping. I removed the ABS function. It's still throwing the same error. Now when I copy the payload from SXMB_MONI and test in Mapping in ESR, it's working fine. But the same source file throws error in SXMB_MONI. The xml that works in Test tab should certainly work in SXMB_MONI also, shouldn't it?
    So I guess it is a different error.
    Runtime exception occurred during application mapping com/sap/xi/tf/_MM_INFRECMASS_ECC_to_MDM_; com.sap.aii.mappingtool.tf7.MessageMappingException: Runtime exception when processing target-fieldmapping /ns0:MT_INFRECMASS_Receiver/INFREC_Receiver
    I must add that the INFREC_Receiver is the root node of the target file and I have kept it 0..unbounded and fields 0...1. But the source has many segements of the Idoc, so should I change them ?
    Harish Babu

  • JavaFX Runtime, JDK Bundles and Executable Jar's.....

    It appears that a JavaFX applet can be executed/launched so long as JRE v1.6_u14+ has been installed (I believe). I've tested this and machines without a JavaFX SDK installation can run the javafx.com applets.
    But is this also true for an executable jar? What's needed to execute JavaFX desktop applications a bare minimum?

    I haven't tried, but the specified minimal JRE is 1.5. That's why we are restricted to 1.5 classes in JavaFX...
    JavaFX applets are deployed and run by using the dtfx.js script, which check if JavaFX runtime is installed, and if not, download and install it.
    JavaFX desktop applications (in .jar files) must be run through a JNLP file which does the same (check and deploy runtime if needed).
    In theory you can deploy the runtime yourself, to avoid the use of a JNLP file (why?), but I think it will go against the current license.
    At least the JNLP does a number of checks for you, checking you have the right version, upgrading if needed, installing shortcuts, etc.

  • Extracting files from executable jars at runtime

    I'm still pretty new to Java, and I'm trying to find out how (if it's possible) to access files inside jars at runtime. More to the point, I am trying to make a help file for my application, stored as a .txt file. Currently I have the text file in the same directory as the source code, and I am bundling the source directory into an executable jar. However, when the jar is executed, it cannot find the file. There's got to be some mechanism for automatically loading files that are in the source directory. This issue is confused by the fact that I am using Windows XP, and so the default home directory to execute from is the My Programs directory. Any help would be appreciated!

    [url http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html]Class.[url http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)]getResourceAsStream(java.lang.String) is what ye want.
    InputStream is = class.getResourceAsStream("myhelpfile.txt"); will get a file in the folder as your class file.
    InputStream is = class.getResourceAsStream("/myhelpfile.txt"); will get a file in the root of the jar.

  • Wrong target group is executed

    Hi all,
    In the PCUI we have a campaign with 2 target groups under the 'Segments' tab. When we select the first and then press the 'Target Group to Channel' button, in the job log we can see the second target group was executed and not the first. The transfer status of the target groups shows the status we expect (1: Job Ended Without Errors and 2: Job not scheduled) so we could only see something was wrong looking into the job log.
    This happened only twice as we know but we would like to know how this can happen and how this can be prevented. Does anyone has an idea how to solve and clarify our issue?
    Kind regards,
    RS

    Hai,
    I think it is easy to create a target group using CRMD_MKTSEG. Target Group is every time linked with a Campaign. using attributes u create profile sets and using filter values of attributes u create target groups.
    You can check the following link.
    http://help.sap.com/saphelp_crm40sr1/helpdata/en/db/58963eac416f01e10000000a114084/frameset.htm

  • Executing jar from java code, then kill parent java code

    Please suggest if there is any best way around on executing jar from java code then killing parent java code.
    a) I have desktop based java application say "Monitor.java" which runs every 5 minutes.
    b) How can I START external java application say "execute.jar" from Monitor.java THEN EXIT Monitor.java
    I tried various options using "ProcessBuilder" and calling bat file but I need Monitor (parent application to EXIT, immediately after calling child (execute.jar)
    Try1) ProcessBuilder builder = new ProcessBuilder("java -jar execute.jar");          
    Process process = builder.start();
    Try2) Runtime r = Runtime.getRuntime();
    Process p = null;
    p = r.exec(new String[] { "cmd", "/c", "start C:/temp/Test.bat" });

    I have a requirement to transfer data from one db to another db from Java Application Layer.Maybe, maye not. We get all sorts of weird "requirements" - which are nothing but thoughts or proposed solutions.
    But,
    Did the "requirement" mention whether the table existed already or not in the target database? - If not, did it tell you to create it - drop/create it?
    Did the "requirement" deliver some explanation to why this copying was neeeded? - Are we talking replication? - Or a one time cloning?
    Etc, etc,
    Personally I would always argue against a "reuirement" like that. - It just isn't the way to do it. Period.
    Regards
    Peter
    P.S: If you are satisfied with what COPY does, then you could let Java make an OS call and do it from there?

  • Vm arg in executable jar

    Hi,
    I do this to run my java class (because it uses a lot of memory):
    java -Xmx128M Crossword
    and this works fine.
    Now I've made an executable jar to run my class just by double clicking on the jar file. The problem is that I dont know how to make the jar use this VM parameter. I dont want anything external to my jar to have to change. I want to just be able to drop my jar on a different PC (with a JRE installed on it of course) and be able to run the jar just be double clicking it.
    Anyone know how to do this?
    Thanks,
    Jim

    There are of course other solutions.
    For example you write a simple application that starts a VM using Runtime.exec(). That is OS specific (and requires some work for each system.) It exits once it starts the other VM.
    You could even wrap it in a single jar by having passing in a command line parameter that specifies "run real' or 'start with correct memory'.
    I believe one of the properties in System.getProperites() has the VM path.

  • 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

  • Making Executable Jar file using java Application

    Following Program creates the jar file at specified location. but, I wonder why this file does not execute on double clicking on it, in spite of that the Manifest file contain correct main class file name
    //MakJar.java
    import java.io.*;
    public class MakJar
    public static void main(String[] args)throws IOException{
    Process p;
    String str="D:\\Himesh\\JFiles";
    try {
    BufferedWriter out = new BufferedWriter(new FileWriter(str+"\\mainClass.txt"));
    out.write("Main-Class: TestFrame\n");
    out.close();
    } catch (IOException e) {
    try
         p=Runtime.getRuntime().exec("cmd /c D:\\Java6\\jdk1.6.0\\bin\\javac.exe "+str+"\\TestFrame.java");
         p=Runtime.getRuntime().exec("cmd /c D:\\Java6\\jdk1.6.0\\bin\\jar cvmf "+str+"\\mainClass.txt "+str+"\\Demo.jar "+str+"\\*.class");
    catch(IOException e)
    System.err.println("Error on exec() method");
    e.printStackTrace();
    }

    Sir,
    On execute the jar using a "java -jar. . ." command. it gives the error--
    "Exception in thread "main" java.lang.NoClassDefFoundError : TestFrame"
    On Extracting the files from jar file made by the java program,i found that the manifist file ( containing the name of main class) and t the class file are included in the jar file.
    But if I make the jar file manually it works perfectly.I have even reinstalled the java but the problem persists
    Same thing happen if i use MS-DOS batch file.
    ??????If i put the batch file in the same directory and execute it The resulting jar file works,But
    ??????if the batch file is executed from outside the directory The resulting jar file fails execute.
    what should i do???

Maybe you are looking for